Java Reference
In-Depth Information
n
t
o
c
h
a
r
s
Note
The first example using
toCharArray()
generates a new character array.
Therefore, the second example, using the traditional
for
loop, might perform faster.
How It Works
String objects contain methods that can be used for performing various tasks. The solu-
tion to this recipe demonstrates a number of different
String
methods. The
toCharArray()
method can be called against a string in order to break the string in-
to characters and then store those characters in an array. This method is very powerful
and it can save a bit of time when performing this task is required. The result of calling
the
toCharArray()
method is a
char[]
, which can then be traversed using an in-
dex. Such is the case in the solution to this recipe. An enhanced
for
loop is used to it-
erate through the contents of the
char[]
and print out each of its elements.
The string
length()
method is used to find the number of characters contained
within a string. The result is an
int
value that can be very useful in the context of a
for
loop, as demonstrated in the solution to this recipe. In the second example, the
length()
method is used to find the number of characters in the string so that they
can be iterated over using the
charAt()
method. The
charAt()
method accepts an
int
index value as an argument and returns the character that resides at the given in-
dex in the string.
Often the combination of two or more string methods can be used to obtain various
results. In this case, using the
length()
and
charAt(
) methods within the same
code block provided the ability to break down a string into characters.