Java Reference
In-Depth Information
LISTING 3.3
Continued
12: System.out.println(“The index of the character v: “
13: + str.indexOf('v'));
14: System.out.println(“The index of the beginning of the “
15: + “substring \”IBM\”: “ + str.indexOf(“IBM”));
16: System.out.println(“The string in upper case: “
17: + str.toUpperCase());
18: }
19: }
The following is displayed on your system's standard output device when you run the
program:
The string is: Nobody ever went broke by buying IBM
Length of this string: 36
The character at position 5: y
The substring from 26 to 32: buying
The index of the character v: 8
The index of the beginning of the substring “IBM”: 33
The string in upper case: NOBODY EVER WENT BROKE BY BUYING IBM
3
In line 4, you create a new instance of String by using a string literal. The remainder of
the program simply calls different string methods to do different operations on that
string:
Line 5 prints the value of the string you created in line 4: “Nobody ever went
broke by buying IBM” .
n
Line 7 calls the length() method in the new String object. This string has 36
characters.
n
Line 9 calls the charAt() method, which returns the character at the given position
in the string. Note that string positions start at position 0 rather than 1 , so the char-
acter at position 5 is y .
n
Line 11 calls the substring() method, which takes two integers indicating a range
and returns the substring with those starting and ending points. The substring()
method also can be called with only one argument, which returns the substring
from that position to the end of the string.
n
Line 13 calls the indexOf() method, which returns the position of the first instance
of the given character (here, 'v' ). Character literals are surrounded by single quo-
tation marks; if double quotation marks had surrounded the v in line 13, the literal
would be considered a String .
n
 
Search WWH ::




Custom Search