Java Reference
In-Depth Information
"A" is less than "Z"
"To" is greater than "A"
How It Works
You should have no trouble with this example. It declares and initializes three
String
variables:
string1
,
string2
, and
string3
. You then create three further
String
variables that correspond to the
first three strings with double quote characters at the beginning and the end. This is just to simplify the
output statements.
You have an assignment statement that stores the result of comparing
string1
with
string3
:
int result = string1.compareTo(string3);
You can now use the value of
result
to determine how the strings are ordered:
if(result < 0) {
System.out.println(string1Out + " is less than " + string3Out);
} else if(result > 0) {
System.out.println(string1Out + " is greater than " +
string3Out);
} else {
System.out.println(string1Out + " is equal to " + string3Out);
}
The first
if
statement determines whether
string1
is less than
string3
. If it is, then a message is
displayed. If
string1
is not less than
string3
, then either they are equal or
string1
is greater than
string3
. The
else if
statement determines which is the case and outputs a message accordingly.
You compare
string2
with
string1
in the same way.
As with the
equals()
method, the argument to the
compareTo()
method can be any expression that res-
ults in a
String
object.
Accessing String Characters
When you are processing strings, sooner or later you need to access individual characters in a
String
object.
To refer to a character at a particular position in a string you use an index of type
int
that is the offset of the
character position from the beginning of the string.
This is exactly the same principle you used for referencing an array element. The first character in a string
is at position 0, the second is at position 1, the third is at position 2, and so on. However, although the prin-
ciple is the same, the practice is not. You can't use square brackets to access characters in a string — you
must use a method.
Extracting String Characters
You extract a character from a
String
object by using the
charAt()
method. This accepts an integer argu-
ment that is the offset of the character position from the beginning of the string — in other words, an index.
If you attempt to use an index that is less than 0 or greater than the index for the last position in the string,
you cause an exception to be thrown, which causes your program to be terminated. I discuss exactly what