Strings
String Indexing
String s = "HELLOWORLD";
Java uses 0-based indexing for Strings: the first position is indicated by 0, the next position by 1, etc.
\[ \underset{0}{\fbox{ H }} \underset{1}{\fbox{ E }} \underset{2}{\fbox{ L }} \underset{3}{\fbox{ L }} \underset{4}{\fbox{ O }} \underset{5}{\fbox{ W }} \underset{6}{\fbox{ O }} \underset{7}{\fbox{ R }} \underset{8}{\fbox{ L }} \underset{9}{\fbox{ D }} \]
String Objects
A String variable is a reference to a String object. You can use this reference to call String methods with the dot notation:
.length(); // returns 10 s
Substrings
You specify sub-strings by specifying begin
and
end
indices.
The String method substring(begin, end)
returns the
substring with indices in the half-open interval
[begin, end)
, i.e. all indices up to but not including
end
.
.substring(0, 5); // returns "HELLO"
s.substring(5, 10); // returns "WORLD" s
The end
argument has a default value of
length()
. In other words, substring(begin)
is equivalent to substring(begin, length())
, and
returns the substring starting at begin
and including
all the characters through the end of the string.
.substring(5); // returns "WORLD" s
String Comparisons
The equality operator ==
compares two String
references, returning true if they refer to the same Object. Note
that this is different from comparing the values of the
String objects.
To compare String values, you should use the
equals()
method.
.equals(t); // returns true <-> s and t have identical values s