boolean regionMatches(booleanignoreCase,
intstartIndex, Stringstr2,
intstr2StartIndex, intnumChars)
For both versions,startIndexspecifies the index at which the region begins within the
invokingStringobject. TheStringbeing compared is specified bystr2.The index at which
the comparison will start withinstr2is specified bystr2StartIndex. The length of the substring
being compared is passed innumChars.In the second version, ifignoreCaseistrue, the case
of the characters is ignored. Otherwise, case is significant.
startsWith( ) and endsWith( )
Stringdefines two routines that are, more or less, specialized forms ofregionMatches( ).
ThestartsWith( )method determines whether a givenStringbegins with a specified string.
Conversely,endsWith( )determines whether theStringin question ends with a specified
string. They have the following general forms:
boolean startsWith(Stringstr)
boolean endsWith(Stringstr)
Here,stris theStringbeing tested. If the string matches,trueis returned. Otherwise,false
is returned. For example,
"Foobar".endsWith("bar")
and
"Foobar".startsWith("Foo")
are bothtrue.
A second form ofstartsWith( ), shown here, lets you specify a starting point:
boolean startsWith(Stringstr, intstartIndex)
Here,startIndexspecifies the index into the invoking string at which point the search will
begin. For example,
"Foobar".startsWith("bar", 3)
returnstrue.
equals( ) Versus ==
It is important to understand that theequals( )method and the==operator perform two
different operations. As just explained, theequals( )method compares the characters inside
aStringobject. The==operator compares two object references to see whether they refer
to the same instance. The following program shows how two differentStringobjects can
contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
366 Part II: The Java Library