Java Reference
In-Depth Information
EXAMPLE 3-2
Consider the following statements:
String sentence;
String str1;
String str2;
int
index;
3
sentence = "Now is the time for the birthday party.";
The following statements further show how
String
methods work.
Statement
Effect / Explanation
sentence.charAt(16)
Returns:
'f'
In
sentence
, the character at position 16
is
'f'
.
sentence.length()
Returns: 38
The number of characters in sentence is 38.
sentence.indexOf('t')
Returns: 7
This is the index of the first
't'
in
sentence
.
sentence.indexOf("for")
Returns: 16
In
sentence
, the starting index of the
string
"for"
.
sentence.substring(0, 6)
Returns:
"Now is"
In
sentence
, the substring starting at index
0 until the index 5 (= 6 - 1) is
"Now is"
.
sentence.substring(7, 12)
Returns:
"the t"
In
sentence
, the substring starting at index
7 until the index 11 (= 12 - 1) is
"the t"
.
sentence.substring(7, 22)
Returns:
"the time for th"
In
sentence
, the substring starting at index
7 until the index 21 (= 22 - 1) is
"the
time for th"
.
sentence.substring(4, 10)
Returns:
"is the"
In
sentence
, the substring starting at index
4 until the index 9 (= 10 - 1) is
"is the"
.
str1 = "Now is t"
In
sentence
, the substring starting at index 0
until the index 7 (= 8 - 1) is
"Now is t"
.So
the value assigned to
str1
is
"Now is t"
.
str1 = sentence.substring(0, 8);
Search WWH ::
Custom Search