img
The second new constructor supports the new StringBuilder class. It is shown here:
String(StringBuilder strBuildObj)
This constructs a String from the StringBuilder passed in strBuildObj.
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the
length( ) method, shown here:
int length( )
The following fragment prints "3", since there are three characters in the string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Special String Operations
Because strings are a common and important part of programming, Java has added special
support for several string operations within the syntax of the language. These operations
include the automatic creation of new String instances from string literals, concatenation of
multiple String objects by use of the + operator, and the conversion of other data types to a
string representation. There are explicit methods available to perform all of these functions,
but Java does them automatically as a convenience for the programmer and to add clarity.
String Literals
The earlier examples showed how to explicitly create a String instance from an array of
characters by using the new operator. However, there is an easier way to do this using a
string literal. For each string literal in your program, Java automatically constructs a String
object. Thus, you can use a string literal to initialize a String object. For example, the following
code fragment creates two equivalent strings:
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
Because a String object is created for every string literal, you can use a string literal any
place you can use a String object. For example, you can call methods directly on a quoted
string as if it were an object reference, as the following statement shows. It calls the length( )
method on the string "abc". As expected, it prints "3".
System.out.println("abc".length());
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception
to this rule is the + operator, which concatenates two strings, producing a String object as the
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home