Java Reference
In-Depth Information
This code produces the following output:
Length of s1 = 5
Length of s2 = 12
What else might you want to do with a String object? With the length method,
you can figure out how many characters there are in a String , but what about getting
the individual characters themselves? There are several ways to do this, but one of the
most common is to use a method called charAt that returns the character at a spe-
cific location in the string.
This leads us to the problem of how to specify locations in a sequence. Obviously
there is a first character, a second character, and so on, so it makes sense to use an
integer to refer to a specific location. We call this the index.
Index
An integer used to specify a location in a sequence of values. Java generally
uses zero-based indexing (with 0 as the first index value, followed by 1, 2, 3,
and so on).
Each character of a String object is assigned an index value, starting with 0. For
example, for the variable s1 that refers to the string " hello " , the indexes are:
01234
h
e
l
l
o
It may seem intuitive to consider the letter “h” to be at position 1, but there are
advantages to starting with an index of 0. It's a convention that was adopted by the
designers of the C language and that has been followed by the designers of C++ and
Java, so it's a convention you'll have to learn to live with.
For the longer String s2 , the positions are:
0
1
2
3
4
5
6
7
8
9
10
11
h
o
w
3
a
r
e
3
y
o
u
?
Notice that the spaces in this String have positions as well (here, positions 3 and 7).
Also notice that the indexes for a given string always range from 0 to one less than the
length of the string.
Using the charAt method, you can request specific characters of a string. The
return type is char . For example, if you ask for s1.charAt(1) you'll get 'e' (the 'e'
in “hello”). If you ask for s2.charAt(5), you'll get 'r' (the 'r' in “how are you?”).
For any String , if you ask for charAt(0) , you'll get the first character of the string.
When you are working with String objects, you'll often find it useful to write a
for loop to handle the different characters of the String . Because String s are
 
Search WWH ::




Custom Search