Java Reference
In-Depth Information
PITFALL: An Array of Characters Is Not a String
An array of characters, such as the array
a
created below, is conceptually a list of
characters; therefore, it is conceptually like a string:
char
[] a = {'A', ' ', 'B', 'i', 'g', ' ', 'H', 'i', '!'};
However, an array of characters, such as
a
, is not an object of the class
String
. In
particular, the following is illegal in Java:
String s = a;
Similarly, you cannot normally use an array of characters, such as
a
, as an argument
for a parameter of type
String
.
It is, however, easy to convert an array of characters to an object of type
String
. The
class
String
has a constructor that has a single parameter of type
char[]
. So, you can
obtain a
String
value corresponding to an array of characters, such as
a
, as follows:
String s =
new
String(a);
The object
s
will have the same sequence of characters as the array
a
. The object
s
is
an independent copy; any changes made to
a
will have no effect on
s
. Note that this
always uses the entire array
a
.
There is also a
String
constructor that allows you to specify
a
subrange of an array
of characters
a
. For example,
String s2 =
new
String(a, 2, 3);
produces a
String
object with
3
characters from the array
a
starting at index
2
. So, if
a
is as above, then
System.out.println(s2);
outputs
Big
Although an array of characters is not an object of the class
String
, it does have some
things in common with
String
objects. For example, you can output an array of
characters using
println
, as follows,
System.out.println(a);
which produces the output
A Big Hi!
■
provided
a
is as given previously.