Page 122 - Introduction to Programming with Java: A Problem Solving Approach
P. 122

                88 Chapter 3 Java Basics The charAt Method
Suppose you initialize a string variable, animal, with the value “cow”. The animal variable then points to a string object that contains three data items—the three characters ‘c’, ‘o’, and ‘w’. To retrieve a data item (i.e., a character), call the charAt method. charAt stands for character at. The charAt method returns a character at a specified position. For example, if animal calls charAt and specifies the third position, then charAt returns ‘w’ because ‘w’ is the third character in “cow”.
So how do you call the charAt method? Let us answer that question by comparing a charAt method call to a method call that you’re already comfortable with—the println method call. See Figure 3.11.
Figure 3.11 Comparison of charAt method call to println method call Apago PDF Enhancer
In Figure 3.11, note how the charAt method call and the println method call both use this syntax:
<reference-variable> . <method-name> (<argument>)
In the charAt call, animal is the reference variable, charAt is the method name and 2 is the ar- gument. The argument is the tricky part. The argument specifies the index of the character that is to be returned. The positions of characters within a string are numbered starting with index zero, not index one. For emphasis, we say again! The positions in a string start with index zero. So if animal contains “cow,” what does animal.charAt(2) return? As the following table indicates, the ‘w’ character is at index 2, so animal.charAt(2) returns ‘w.’
If you call charAt with an argument that’s negative or that’s equal to or greater than the string’s length, your code will compile OK, but it won’t run properly. For example, suppose you run this program:
public class Test
     argument (2 is the index position of the third character in animal) animal.charAt(2)
reference variable method name argument (the message that is to be printed)
System.out.println("Hello, world!");
                 index:
 0
 1
 2
 “cow” string’s characters:
  c
o
 w
  {
 public static void main(String[] args)
   }
{
}
String animal = "sloth";
System.out.println("Last character: " + animal.charAt(5));
i
i
n
n
a
a
p
pp
p
r
ro
o
p
pr
r
i
i
a
a
t
te
e
i
i
n
n
d
d
e
e
x
x
⎫⎬⎭ ⎫⎬⎭
⎫⎬
⎭
⎫
⎬ ⎭
⎫ ⎬
⎭

































   120   121   122   123   124