Java Reference
In-Depth Information
String literals
The String class represents text as a string of characters. Because programs usually
communicate with their users through the written word, the ability to manipulate
strings of text is quite important in any programming language. In Java, strings are
objects; the data type used to represent text is the String class. Modern Java pro‐
grams usually use more string data than anything else.
Accordingly, because strings are such a fundamental data type, Java allows you to
include text literally in programs by placing it between double-quote ( " ) characters.
For example:
a x
String name = "David" ;
System . out . println ( "Hello, " + name );
Don't confuse the double-quote characters that surround string literals with the
single-quote (or apostrophe) characters that surround char literals. String literals
can contain any of the escape sequences char literals can (see Table 2-2 ). Escape
sequences are particularly useful for embedding double-quote characters within
double-quoted string literals. For example:
String story = "\t\"How can you stand it?\" he asked sarcastically.\n" ;
String literals cannot contain comments and may consist of only a single line. Java
does not support any kind of continuation-character syntax that allows two separate
lines to be treated as a single line. If you need to represent a long string of text that
does not fit on a single line, break it into independent string literals and use the +
operator to concatenate the literals. For example:
// This is illegal; string literals cannot be broken across lines.
String x = "This is a test of the
emergency broadcast system" ;
String s = "This is a test of the " + // Do this instead
"emergency broadcast system" ;
This concatenation of literals is done when your program is compiled, not when it is
run, so you do not need to worry about any kind of performance penalty.
Type literals
The second type that supports its own special object literal syntax is the class named
Class . Instances of the Class class represent a Java data type, and contain metadata
about the type that is referred to. To include a Class object literally in a Java pro‐
gram, follow the name of any data type with .class . For example:
Class <?> typeInt = int . class ;
Class <?> typeIntArray = int []. class ;
Class <?> typePoint = Point . class ;
Search WWH ::




Custom Search