System.out.println("b2 = " + b2);
System.out.println("b3 = " + b3);
}
}
Here is its output:
b1 = false
b2 = true
b3 = false
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
significant. 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 throwing 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 booleanstartsWith(String prefix, int start)
Returns true if this String starts (at start) with the given prefix.
public booleanstartsWith(String prefix)
Equivalent to startsWith(prefix,0).
public booleanendsWith(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);
This does not compare the contents of the two strings. It compares one object reference (str) to another (the
string object representing the literal "¿Peña?"). Even if str contains the string "¿Peña?" this ==
expression will almost always yield false because the two strings will be held in different objects. Using ==
on objects only tests whether the two references refer to the same object, not whether they are equivalent
objects.
However, any two string literals with the same contents will refer to the same String object. For example,
== works correctly in the following code: