Java Reference
In-Depth Information
String text = "To be or not to be"; // Define a string
byte[] textArray = text.getBytes(); // Get equivalent byte array
The byte array textArray contains the same characters as in the String object, but stored as 8-bit char-
acters. The conversion of characters from Unicode to 8-bit bytes is in accordance with the default encoding
for your system. This typically means that the upper byte of the Unicode character is discarded, resulting
in the ASCII equivalent. Of course, it is quite possible that a string may contain Unicode characters that
cannot be represented in the character encoding in effect on the local machine. In this case, the effect of the
getBytes() method is unspecified.
Creating String Objects from Character Arrays
The String class also has a static method, copyValueOf() , to create a String object from an array of type
char[] .Recall that you can use a static method of a class even if no objects of the class exist.
Suppose you have an array defined as follows:
char[] textArray = {'T', 'o', ' ', 'b', 'e', ' ', 'o', 'r', ' ',
'n', 'o', 't', ' ', 't', 'o', ' ', 'b', 'e' };
You can create a String object encapsulating these characters as a string with the following statement:
String text = String.copyValueOf(textArray);
This results in the object text referencing the string "To be or not to be" .
You can achieve the same result like this:
String text = new String(textArray);
This calls a constructor for the String class, which creates a new object of type String that encapsulates
a string containing the characters from the array. The String class defines several constructors for defining
String objects from various types of arrays. You learn more about constructors in Chapter 5.
Another version of the copyValueOf() method can create a string from a subset of the array elements. It
requires two additional arguments to specify the index of the first character in the array to be extracted and
the count of the number of characters to be extracted. With the array defined as previously, the statement
String text = String.copyValueOf(textArray, 9, 3);
extracts three characters starting with textArray[9] , so text contains the string "not" after this operation.
There's a class constructor that does the same thing:
String text = new String(textArray, 9, 3);
The arguments are the same here as for the copyValueOf() method, and the result is the same.
MUTABLE STRINGS
Search WWH ::




Custom Search