img
ASCII character set. Because 8-bit ASCII strings are common, the String class provides
constructors that initialize a string when given a byte array. Their forms are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to specify a
subrange. In each of these constructors, the byte-to-character conversion is done by using
the default character encoding of the platform. The following program illustrates these
constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
This program generates the following output:
ABCDEF
CDE
Extended versions of the byte-to-string constructors are also defined in which you can
specify the character encoding that determines how bytes are converted to characters. However,
most of the time, you will want to use the default encoding provided by the platform.
NOTE  The contents of the array are copied whenever you create a String object from an array. If you
OTE
modify the contents of the array after you have created the string, the String will be unchanged.
You can construct a String from a StringBuffer by using the constructor shown here:
String(StringBuffer strBufObj)
String Constructors Added by J2SE 5
J2SE 5 added two constructors to String. The first supports the extended Unicode character
set and is shown here:
String(int codePoints[ ], int startIndex, int numChars)
Here, codePoints is an array that contains Unicode code points. The resulting string is
constructed from the range that begins at startIndex and runs for numChars.
NOTE  A discussion of Unicode code points and how they are handled by Java is found in Chapter 16.
OTE
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home