Java Reference
In-Depth Information
The first comparison yields
false
because the character at position 6 of
the main string is
'l'
and the character at position 0 of the other string
is
'L'
. The second comparison yields
TRue
because case is not signific-
ant. The third comparison yields
false
because the comparison length is
now 5 and the two strings are not the same over five characters, even
ignoring case.
In querying methods, such as
regionMatches
and those we mention next,
any invalid indexes simply cause
false
to be returned rather than throw-
ing exceptions. Passing a
null
argument when an object is expected
generates a
NullPointerException
.
You can do simple tests for the beginnings and ends of strings by using
startsWith
and
endsWith
:
public boolean
startsWith(String prefix, int start)
Returns
true
if this
String
starts (at
start
) with the given
pre-
fix
.
public boolean
startsWith(String prefix)
Equivalent to
startsWith(prefix,0)
.
public boolean
endsWith(String suffix)
Returns
TRue
if this
String
ends with the given
suffix
.
13.2.3. String Literals, Equivalence and Interning
In general, using
==
to compare strings will give you the wrong results.
Consider the following code:
if (str == "¿Peña?")
answer(str);