Java Reference
In-Depth Information
and a carriage return, respectively. This violates the rule that a string literal cannot be continued in two lines. For
example, in the early stages of compilation " Hel\u000Alo" is translated into the following, which is an invalid string
literal and generates a compiler error:
"Hel
lo"
it is a compile-time error to use Unicode escapes \u000A and \u000D in a string literal to represent a line feed
and a carriage return, respectively. You must use the escape sequences of \n and \r instead.
Tip
What is a CharSequence?
A CharSequence is an interface in the java.lang package. I discuss interfaces in Beginning Java Language Features
(ISBN 978-1-4302-6658-7). For now, you can think of a CharSequence as an object that represents a readable
sequence of characters. String , StringBuffer , and StringBuilder , to name a few, are instances of CharSequence .
They provide read-only methods to read some properties and the content of the sequence of characters represented
by them. In the API documentation for the String class, you will see arguments of many methods declared as
CharSequence . You can always pass a String , a StringBuilder , or a StringBuffer where a CharSequence is required.
Creating String Objects
The String class contains many constructors that can be used to create a String object. The default constructor lets
you create a String object with an empty string as its content. For example, the following statement creates an empty
String object and assigns its reference to the emptyStr variable:
String emptyStr = new String();
The String class contains a constructor, which takes another String object as an argument.
String str1 = new String();
String str2 = new String(str1); // Passing a String as an argument
Now str1 represents the same sequence of characters as str2 . At this point, both str1 and str2 represent an
empty string. You can also pass a string literal to this constructor.
String str3 = new String("");
String str4 = new String("Have fun!");
After these two statements are executed, str3 will refer to a String object, which has an empty string (a sequence
of zero characters) as its content, and str4 will refer to a String object, which has " Have fun!" as its content.
 
 
Search WWH ::




Custom Search