362 94 3MB
English Pages 216 [212] Year 2016
Java Precisely Third Edition
Peter Sestoft
Java Precisely Third Edition
The MIT Press Cambridge, Massachusetts London, England
c 2016 Massachusetts Institute of Technology All rights reserved. No part of this book may be reproduced in any form by any electronic or mechanical means (including photocopying, recording, or information storage and retrieval) without permission in writing from the publisher. MIT Press books may be purchased at special quantity discounts for business or sales promotional use. This book was set in Times by the author using LATEX and was printed and bound in the United States of America. Library of Congress Cataloging-in-Publication Data Names: Sestoft, Peter. Title: Java precisely / Peter Sestoft. Description: Third edition. | Cambridge, MA : The MIT Press, [2016] | Includes bibliographical references and index. Identifiers: LCCN 2015038522 | ISBN 9780262529075 (pbk. : alk. paper) Subjects: LCSH: Java (Computer program language) Classification: LCC QA76.73.J38 S435 2015 | DDC 005.13/3–dc23 LC record available at http://lccn.loc.gov/2015038522
10 9
8 7
6 5
4 3
2 1
Contents Preface
xi
Notational Conventions
xii
1
Running Java: Compilation, Loading, and Execution
2
2
Names and Reserved Names
2
3
Java Naming Conventions
2
4
Comments and Program Layout
2
5
Types 5.1 Primitive Types . . . . . . . . . . . . . . . . . . . . . 5.2 Reference Types . . . . . . . . . . . . . . . . . . . . 5.3 Array Types . . . . . . . . . . . . . . . . . . . . . . 5.4 Boxing: Wrapping Primitive Types as Reference Types 5.5 Subtypes and Compatibility . . . . . . . . . . . . . . 5.6 Signatures and Subsumption . . . . . . . . . . . . . . 5.7 Type Conversion . . . . . . . . . . . . . . . . . . . .
. . . . . . .
4 4 4 4 4 6 6 6
6
Variables, Parameters, Fields, and Scope 6.1 Values Bound to Variables, Parameters, or Fields . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3 Scope of Variables, Parameters, and Fields . . . . . . . . . . . . . . . . . . . . . . . . . . .
8 8 8 8
7
Strings 7.1 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10 12
8
Arrays 8.1 Array Creation and Access 8.2 Array Initializers . . . . . 8.3 Multidimensional Arrays . 8.4 The Utility Class Arrays .
9
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
16 16 16 18 18
Classes 9.1 Class Declarations and Class Bodies . . . . . . . . . . . . . . . . . . . 9.2 Top-Level Classes, Nested Classes, Member Classes, and Local Classes 9.3 Class Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.4 The Class Modifiers public, final, abstract . . . . . . . . . . . . . 9.5 Subclasses, Superclasses, Class Hierarchy, Inheritance, and Overriding 9.6 Field Declarations in Classes . . . . . . . . . . . . . . . . . . . . . . . 9.7 The Member Access Modifiers private, protected, public . . . . . 9.8 Method Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.9 Parameter Arrays and Variable-Arity Methods . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
22 22 22 22 24 24 26 26 28 30
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
vi Contents
9.10 9.11 9.12 9.13
Constructor Declarations . . . . . . . . . . . . . . . . . . . . . . . Nested Classes, Member Classes, Local Classes, and Inner Classes Anonymous Classes . . . . . . . . . . . . . . . . . . . . . . . . . Initializer Blocks, Field Initializers, and Initializers . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
30 32 32 32
10 Classes and Objects in the Computer 10.1 What Is a Class? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2 What Is an Object? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.3 Inner Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
34 34 34 34
11 Expressions 11.1 Table of Expression Forms . . . . . . . . 11.2 Arithmetic Operators . . . . . . . . . . . 11.3 Logical Operators . . . . . . . . . . . . 11.4 Bitwise Operators and Shift Operators . . 11.5 Assignment Expressions . . . . . . . . . 11.6 Conditional Expressions . . . . . . . . . 11.7 Object Creation Expressions . . . . . . . 11.8 Instance Test Expressions . . . . . . . . 11.9 Field Access Expressions . . . . . . . . 11.10 The Current Object Reference this . . . 11.11 Type Cast Expression . . . . . . . . . . 11.12 Method Call Expressions . . . . . . . . . 11.13 Lambda Expressions (Java 8.0) . . . . . 11.14 Method Reference Expressions (Java 8.0)
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
36 36 38 38 38 40 40 40 40 42 42 42 44 48 48
12 Statements 12.1 Expression Statements . . . . . . . . . . . . . . . . 12.2 Block Statements . . . . . . . . . . . . . . . . . . . 12.3 The Empty Statement . . . . . . . . . . . . . . . . 12.4 Choice Statements . . . . . . . . . . . . . . . . . . 12.5 Loop Statements . . . . . . . . . . . . . . . . . . . 12.6 Returns, Labeled Statements, Exits, and Exceptions 12.7 The Try-with-Resources Statement . . . . . . . . . 12.8 The assert Statement . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
52 52 52 52 54 56 60 64 64
13 Interfaces 13.1 Interface Declarations . . . . . . . . . . . . . . . 13.2 Classes Implementing Interfaces . . . . . . . . . . 13.3 Default and Static Methods on Interfaces (Java 8.0) 13.4 Annotation Type Declarations . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
66 66 66 68 68
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . .
14 Enum Types
70
15 Exceptions, Checked and Unchecked
72
16 Compilation, Source Files, Class Names, and Class Files
74
Contents vii
17 Packages and Jar Files
74
18 Mathematical Functions
76
19 String Builders and String Buffers
78
20 Threads, Concurrent Execution, and Synchronization 20.1 Threads and Concurrent Execution . . . . . . . . . . . 20.2 Locks and the synchronized Statement . . . . . . . . 20.3 Operations on Threads . . . . . . . . . . . . . . . . . . 20.4 Operations on Locked Objects . . . . . . . . . . . . . . 20.5 The Java Memory Model and Visibility Across Threads
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
21 Generic Types and Methods 21.1 Generics: Safety, Generality, and Efficiency . . . . . 21.2 Generic Types, Type Parameters, and Type Instances 21.3 How Can Type Instances Be Used? . . . . . . . . . 21.4 Generic Classes . . . . . . . . . . . . . . . . . . . 21.5 Constraints on Type Parameters . . . . . . . . . . . 21.6 How Can Type Parameters Be Used? . . . . . . . . 21.7 Generic Interfaces . . . . . . . . . . . . . . . . . . 21.8 Generic Methods . . . . . . . . . . . . . . . . . . . 21.9 Wildcard Type Arguments . . . . . . . . . . . . . . 21.10 The Raw Type . . . . . . . . . . . . . . . . . . . . 21.11 The Implementation of Generic Types and Methods
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
88 . 88 . 88 . 88 . 90 . 92 . 92 . 94 . 96 . 98 . 100 . 100
22 Generic Collections and Maps 22.1 Interface Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.2 Interface List and Its Implementations LinkedList and ArrayList . . 22.3 Interface Set and Its Implementations HashSet and LinkedHashSet . 22.4 Interface SortedSet and Implementation TreeSet . . . . . . . . . . . . 22.5 Interface Map and Implementation HashMap . . . . . . . . . . . 22.6 Interface SortedMap and Implementation TreeMap . . . . . . . . 22.7 Going through a Collection: Interfaces Iterator and Iterable . . . . . . . 22.8 Interface ListIterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.9 Equality, Hash Codes, and Comparison . . . . . . . . . . . . . . . . . . . . . . 22.10 The Comparator Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.11 The Utility Class Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.12 Choosing the Right Collection Class or Map Class . . . . . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
102 104 105 106 106 108 110 112 114 114 116 118 120
23 Functional Interfaces (Java 8.0) 23.1 Functional Programming . . . . . . . . . . . . . . . . . 23.2 Generic Functional Interfaces . . . . . . . . . . . . . . 23.3 Primitive-Type Specialized Functional Interfaces . . . . 23.4 Covariance and Contravariance in Functional Interfaces 23.5 Interface Function . . . . . . . . . . . . . . . . . 23.6 Interface UnaryOperator . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
122 122 124 124 126 126 126
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
80 80 82 84 84 86
viii Contents
23.7 23.8 23.9 23.10 23.11
Interfaces Predicate and BiPredicate . Interfaces Consumer and BiConsumer Interface Supplier . . . . . . . . . . . . . . Interface BiFunction . . . . . . . . . . Interface BinaryOperator . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
128 128 128 130 130
24 Streams for Bulk Data (Java 8.0) 24.1 Creating Streams . . . . . . . . . . . . . . . . . . . . . . . . 24.2 Stream Builders . . . . . . . . . . . . . . . . . . . . . . . . 24.3 Methods on Streams . . . . . . . . . . . . . . . . . . . . . . 24.4 Numeric Streams: DoubleStream, IntStream, and LongStream 24.5 Summary Statistics for Numeric Streams . . . . . . . . . . . 24.6 Collectors on Streams . . . . . . . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
132 134 134 136 140 140 142
25 Class Optional (Java 8.0)
146
26 Input and Output 26.1 Creating an IO Stream from Another One . . . . . . . . . . . . . . 26.2 Kinds of Input and Output Methods . . . . . . . . . . . . . . . . . 26.3 Imports, Exceptions, Thread Safety . . . . . . . . . . . . . . . . . 26.4 Sequential Character Input: Readers . . . . . . . . . . . . . . . . . 26.5 Sequential Character Output: Writers . . . . . . . . . . . . . . . . 26.6 Printing Primitive Data to a Character Stream: PrintWriter . . . . . 26.7 The Appendable Interface and the CharSequence Interface . . . . . 26.8 Reading Primitive Data from a Character Stream: StreamTokenizer 26.9 Sequential Byte Input: InputStream . . . . . . . . . . . . . . . . . 26.10 Sequential Byte Output: OutputStream . . . . . . . . . . . . . . . 26.11 Binary Input-Output of Primitive Data: DataInput and DataOutput . 26.12 Serialization of Objects: ObjectInput and ObjectOutput . . . . . . 26.13 Buffered Input and Output . . . . . . . . . . . . . . . . . . . . . . 26.14 Random Access Files: RandomAccessFile . . . . . . . . . . . . . 26.15 Files, Directories, and File Descriptors . . . . . . . . . . . . . . . 26.16 Thread Communication: PipedInputStream and PipedOutputStream 26.17 Socket Communication . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
148 149 150 150 152 153 154 154 156 158 159 160 162 164 166 168 168 170
27 Reflection 27.1 Reflective Use of Types: The Class Class . . . . . . . . 27.2 Reflection: The Field Class . . . . . . . . . . . . . . . . . 27.3 Reflection: The Method Class and the Constructor Class 27.4 Exceptions Thrown When Using Reflection . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
172 172 174 174 174
. . . .
. . . .
. . . .
. . . .
28 Metadata Annotations
176
29 What Is New in Java 8.0
178
References
180
Contents ix
Index
181
Preface This third edition of Java Precisely gives a concise description of the Java programming language, version 8.0. It is a quick reference for the reader who has already learned (or is learning) Java from a standard textbook and who wants to know the language in more detail. The book presents the entire Java programming language and essential parts of the class libraries: the collection classes, the input-output classes, the stream library and its facilities for parallel programming, and the functional interfaces used for that. General rules are shown on left-hand pages mostly, and corresponding examples are shown on right-hand pages only. All examples are fragments of legal Java programs. The complete ready-to-run example programs are available from the book Web site: www.itu.dk/people/sestoft/javaprecisely. This third edition adds material about new methods for functional parallel processing of arrays (section 8.4); default and static methods on interfaces (section 13.3); the memory visibility effects of volatile and final (section 20.5); new comparator methods (section 22.10); functional interfaces (chapter 23) and the related lambda expressions (section 11.13) and method reference expressions (section 11.14); stream processing, including parallel programming and collectors (chapter 24); and the Optional class (chapter 25). In general the book has been updated for the changes from Java 5.0 to Java 8.0. The final chapter 29 summarizes and illustrates the new features of Java 8.0 and compares them to the C# programming language. The book does not cover garbage collection, non-blocking input-output, the executor framework, finalization and weak references, details of IEEE 754 floating-point numbers, or Javadoc. Acknowledgments Thanks to Rasmus Lund, Niels Hallenberg, Hans Henrik Løvengreen, Christian Gram, Jan Clausen, Anders Peter Ravn, Bruce Conrad, Brendan Humphreys, Hans Rischel, Ken Friis Larsen, Dan Becker, Mads Jeppe Tarp-Johansen, Kasper Østerbye, Kasper Bilsted Graversen, Søren Eduard Jacobsen, Paul van Bemmelen, Axel Tobias Schreiner, David Hemmendinger, Baris Aktemur, Jakob Bendsen, Jan Schoubo, and all the anonymous reviewers and copy editors for their useful comments, suggestions, and corrections. Special thanks to Rasmus Lund for letting me adapt his collections diagram for this book, and to Kasper Østerbye for campaigning for a reflection chapter and providing a first draft of it. It was a pleasure to work with Robert Prior, Valerie Geary, Deborah Cantor-Adams, Krista Magnuson, Marc Lowenthal, Marie Lufkin Lee, Virginia Crossman, and Kathleen Hensley at The MIT Press. Thanks also to the IT University of Copenhagen, Denmark, for support.
Notational Conventions Symbol a b C cmp cs cseq E e f I i m o p s supp sig t T, U, K, V u v x xs
Meaning Expression or value of array type Boolean or byte array Class Comparator or Comparer Character array (type char[]) Character sequence (type CharSequence) Exception type Expression Field or function Interface Expression or value of integer type Method Expression or value of object type Package or predicate Expression or value of type String Expression or value of type Supplier Signature of method or constructor Type (primitive type or reference type) Type parameter in generic type or method Expression or value of thread type Value of any type Variable or parameter or field or array element Stream
Java Precisely
2
Comments and Program Layout
1 Running Java: Compilation, Loading, and Execution Before a Java program can be executed, it must be compiled and loaded. The compiler checks that the Java program is legal: that the program conforms to the Java syntax, that operators (such as +) are applied to operands (such as 5 and x) of the correct type, and so on. If so, the compiler generates class files. Execution may then be started by loading the class files. Thus running a Java program involves three stages: compilation (checks that the program is well-formed), loading (loads and initializes classes), and execution (runs the code). This holds also for a program run from integrated development environments such as Eclipse or IntelliJ.
2 Names and Reserved Names A legal name (of a variable, method, field, parameter, class, interface or package) starts with a letter or dollar sign ($) or underscore (_), and continues with zero or more letters or dollar signs or underscores or digits (0–9). Avoid dollar signs in class and interface names. Uppercase letters and lowercase letters are considered distinct. A legal name cannot be one of the following reserved names: abstract assert boolean break byte case catch
char class const continue default do double
else enum extends false final finally float
for goto if implements import instanceof int
interface long native new null package private
protected public return short static strictfp super
switch synchronized this throw throws transient true
try void volatile while
3 Java Naming Conventions The following naming conventions are often followed, although not enforced by Java: • If a name is composed of several words, then each word (except possibly the first one) begins with an uppercase letter. Examples: setLayout, addLayoutComponent. • Names of variables, fields, and methods begin with a lowercase letter. Examples: vehicle, myVehicle. • Names of classes and interfaces begin with an uppercase letter. Examples: Cube, ColorCube. • Named constants (such as final static fields and enum values) are written entirely in uppercase, and the parts of composite names are separated by underscores (_). Examples: CENTER, MAX_VALUE. • Package names are sequences of dot-separated lowercase names. Example: java.awt.event. For uniqueness, they are often prefixed with reverse domain names, as in com.sun.xml.util.
4 Comments and Program Layout Comments have no effect on the execution of the program but may be inserted anywhere to help humans understand the program. There are two forms: one-line comments and delimited comments. Program layout has no effect on the computer’s execution of the program but is used to help humans understand the structure of the program.
Comments and Program Layout 3
Example 1 Comments class Comment { // This is a one-line comment; it extends to the end of the line. /* This is a delimited comment, extending over several lines. */ int /* This delimited comment extends over part of a line */ x = 117; }
Example 2 Recommended Program Layout Style For reasons of space this layout style is not always followed in this book. class Layout { int x; Layout(int x) { this.x = x; } int sum(int y) { if (x > 0) { return x + y; } else if (x < 0) { int res = -x + y; return res * 117; } else { // x == 0 int sum = 0; for (int i=0; i= 1) && (day y) maxyz = z; else maxyz = y; }
Example 7 Scope of Fields, Parameters, and Variables This program declares five variables or fields, all called x, and shows where each one is in scope (visible). The variables and fields are labeled #1, . . . , #5 for reference. class Scope { ... void m1(int ... } ... void m2(int ... } ... void m3(int ... int x; ... } ... void m4(int ... { int x; ... } ... { int x; ... } ... } ... int x; ... }
x) {
v2) {
v3) {
v4) {
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
Declaration of parameter x (#1) x #1 in scope
x #5 in scope
x #5 in scope Declaration of variable x (#2) x #2 in scope
x #5 in scope Declaration of variable x (#3) x #3 in scope x #5 in scope Declaration of variable x (#4) x #4 in scope x #5 in scope
Declaration of field x (#5) x #5 in scope
10 Strings
7 Strings A string is an object of the predefined class String. It is immutable: once created it cannot be changed. A string literal is a sequence of characters within double quotes: "New York", "A38", "", and so on. Internally, a character is stored as a number using the Unicode [1] character encoding, whose character codes 0–127 coincide with the old ASCII encoding. String literals and character literals may use character escape sequences: Escape Code \b \t \n \f \r \" \’ \\ \ddd \udddd
Meaning backspace horizontal tab newline form feed (page break) carriage return the double quote character the single quote character the backslash character the character whose character code is the three-digit octal number ddd the character whose character code is the four-digit hexadecimal number dddd
A character escape sequence represents a single character. Since the letter A has code 65 (decimal), which is written 101 in octal and 0041 in hexadecimal, the string literal "A\101\u0041" is the same as "AAA". If s1 and s2 are expressions of type String and v is an expression of any type, then • s1.length() of type int is the length of s1, that is, the number of characters in s1. • s1.equals(s2) of type boolean is true if s1 and s2 contain the same sequence of characters, and false otherwise; equalsIgnoreCase is similar but does not distinguish lowercase and uppercase. • s1.charAt(i) of type char is the character at position i in s1, counting from 0. If the index i is less than 0, or greater than or equal to s1.length(), then StringIndexOutOfBoundsException is thrown. • s1.toString() of type String is the same object as s1. • String.valueOf(v) returns the string representation of v, which can have any primitive type (section 5.1) or reference type. When v has reference type and is not null, then it is converted using v.toString(); if it is null, then it is converted to the string "null". Any class C inherits from Object a default toString method that produces strings of the form C@2a5734, where 2a5734 is some memory address, but toString may be overridden to produce more useful strings. • s1 + s2 has the same meaning as s1.concat(s2): it constructs the concatenation of s1 and s2, a new String consisting of the characters of s1 followed by the characters of s2. Both s1 + v and v + s1 are evaluated by converting v to a string with String.valueOf(v), thus using v.toString() when v has reference type, and then concatenating the resulting strings. • s1.compareTo(s2) returns a negative integer, zero, or a positive integer, according as s1 precedes, equals, or follows s2 in the usual lexicographical ordering based on the Unicode [1] character encoding. If s1 or s2 is null, then the exception NullPointerException is thrown. Method compareToIgnoreCase is similar but does not distinguish lowercase and uppercase. • s1.substring(int i, int j) returns a new String of the characters from s1 with indexes i..(j-1). Throws IndexOutOfBoundsException if ij or j>s1.length. • s1.subSequence(int i, int j) is like substring but returns a CharSequence (section 26.7). • More String methods are described in the Java class library documentation [2].
Strings 11
Example 8 Equality of Strings and the Subtlety of the (+) Operator String s1 = "abc"; String s2 = s1 + ""; // New object, but contains same text as s1 String s3 = s1; // Same object as s1 String s4 = s1.toString(); // Same object as s1 // The following statements print false, true, true, true, true: System.out.println("s1 and s2 identical objects: " + (s1 == s2)); System.out.println("s1 and s3 identical objects: " + (s1 == s3)); System.out.println("s1 and s4 identical objects: " + (s1 == s4)); System.out.println("s1 and s2 contain same text: " + (s1.equals(s2))); System.out.println("s1 and s3 contain same text: " + (s1.equals(s3))); // These two statements print 35A and A1025 because (+) is left-associative: System.out.println(10 + 25 + "A"); // Same as (10 + 25) + "A" System.out.println("A" + 10 + 25); // Same as ("A" + 10) + 25
Example 9 Concatenating All Command Line Arguments When concatenating many strings, use a string builder instead (chapter 19 and example 104). public static void main(String[] args) { String res = ""; for (int i=0; i where Shop is a generic type from example 130; a wildcard cannot be used as a type on its own. A wildcard type is useful when one must give a type argument in a generic type or method but does want to specify the exact type. There are three forms of wildcard types:
is a shop that deals in some unknown type of object. The shop might be a Shop or a Shop or a Shop. Therefore we know only that what we buy from the shop is an Object; and we cannot sell anything to the shop at all, not knowing the type of objects it will accept. A Shop can be given (assigned or passed) a value of type Shop for any type t. A variable b of type Shop
Vehicle Shop, Shop + + + + − − − − + − − − −
Shop, the sellTo-method will accept neither Car nor Sedan nor Vehicle (because the actual element type T might be completely unrelated to these types; say, type Painting), and the object returned by the buyFrom-method could be assigned to a variable of type Object, but not Vehicle nor Car nor Sedan (again because the actual element type T might be completely unrelated to these types). For a Shop