Java Reference
In-Depth Information
This will copy characters from
text
at index positions 9 to 11 inclusive, so
textArray[0]
will be '
n
',
textArray[1]
will be '
o
', and
textArray[2]
will be '
t
'.
You can also extract characters into a
byte
array using the
getBytes()
method in the class
String
.
This converts the original string characters into the character encoding used by the underlying
operating system - which is usually ASCII. For example:
String text = "To be or not to be"; // Define a string
byte[] textArray = text.getBytes(); // Get equivalent byte array
The
byte
array
textArray
will contain the same characters as in the
String
object, but stored as 8-
bit characters. The conversion of characters from Unicode to 8-bit bytes will be in accordance with the
default encoding for your system. This will typically mean that the upper byte of the Unicode character
is discarded resulting in the ASCII equivalent.
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[]
. You will recall that a static method of a class can be used even if no objects of the class exist.
Suppose you have an array defined as:
char[] textArray = {'T', 'o', ' ', 'b', 'e', ' ', 'o', 'r', ' ',
'n', 'o', 't', ' ', 't', 'o', ' ', 'b', 'e' };
You can then create a
String
object with the statement:
String text = String.copyValueOf(textArray);
This will result in the object
text
referencing the string
To
be
or
not
to
be
.
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
will contain the string
not
after
this operation.
StringBuffer Objects
String
objects cannot be changed, but we have been creating strings that are combinations and
modifications of existing
String
objects, so how is this done? Java has another standard class for
defining strings,
StringBuffer
, and a
StringBuffer
object can be altered directly. Strings that can
be changed are often referred to as
mutable strings
whereas a
String
object is an
immutable string
.
Java uses objects of the class
StringBuffer
internally to perform many of the operations on
String
objects. You can use a
StringBuffer
object whenever you need a string that you can change directly.