Java Reference
In-Depth Information
method and the name of the package containing the class ; you must import the
class ; and you must know the method name, its parameters, and what the method does.
However, because the Java system automatically makes the class String available, you
do not need to import this class . Therefore, in order to use a String method, you
need to know its name, parameters, and what the method does.
Recall that a string (literal) is a sequence of 0 or more characters, and string literals are
enclosed in double quotation marks. The index (position) of the first character is 0 , the
index of the second character is 1 , and so on. The length of a string is the number of
characters in it, not the largest index.
If length denotes the length of a string and length is not zero (that is, string is not
null), then length - 1 gives the index of the last character in the string.
The general expression to use a String method on a String variable is:
StringVariable.StringMethodName(parameters)
In this statement, the variable name and the method name are separated with the dot ( . ).
For example, if name is a String variable, and name = "Lisa Johnson" , then the value
of the expression
name.length()
is 12 .
Table 3-1 lists commonly used methods of the class String . Suppose that sentence is
a String . Suppose that sentence = "Programming with Java"; . Then each character
in sentence and its position is as follows:
sentence = "Programming with Java";
P r o
g
r
a
m
m
i
n
g
' ' w
i
t
h
' ' J a
v
a
0
1
2
3
4
5
6
7
8
9
10
11
12 13 14 15
16
17 18
19
20
TABLE 3-1 Some Commonly Used String Methods
char charAt( int index)
//Returns the character at the position specified by index
//Example: sentence.charAt(3) returns 'g'
int indexOf( char ch)
//Returns the index of the first occurrence of the character
//specified by ch; If the character specified by ch does not
//appear in the string, it returns -1
//Example: sentence.indexOf('J') returns 17
//
sentence.indexOf('a') returns 5
 
Search WWH ::




Custom Search