Java Reference
In-Depth Information
string1 is now: Too many cooks
string1.equals(string3) is true. so strings are equal.
Test 2
string3 is now: TOO many cooks
string1 is now: Too many cooks
string1.equals(string3) is false so strings are not equal.
string1.equalsIgnoreCase(string3) is true so strings are equal ignoring case
.
How It Works
Before we look in detail at how the program works, let's first take some time to look at how the method
calls that pepper the code are put together.
In the
if
expression, we've called the method
equals()
of the object
string1
to test for equality with
string3
. This is the syntax we have been using to call the method
println()
in the object
out
. In
general, to call a method belonging to an object you write the object name, then a period, then the name of
the method. The parentheses following the method name enclose the information to be passed to the
method -
string3
in this case. The general form for calling a method for an object is shown below.
We will learn more about this in Chapter 5, when we look at how to define our own
classes. For the moment, just note that you don't necessarily need to pass any
arguments to a method. On the other hand there can be several. It all depends on how
the method was defined in the class.
The
equals()
method requires one argument that you put between the parentheses. This must be the
String
object that is to be compared with the original object. The method returns
true
if the value
passed to it (
string3
in our example) is identical to the string pointed to by the
String
object that
owns the method, in this case
string1
. As you may have already guessed, we could just as well call the
equals()
method for the object
string3
, and pass
string1
as the argument to compare the two
strings. In this case, the expression to call the method would be:
string3.equals(string1)
and we would get exactly the same result.
Looking at the program code, after outputting the values of
string3
and
string1
, the next line
shows that calling the
equals()
method for
string1
with
string3
as the argument returns
true
.
After the
if
, we make
string3
reference a new string. We then compare the values of
string1
and
string3
once more, and, of course, the result of the comparison is now
false
.
Finally we compare
string1
with
string3
using the
equalsIgnoreCase()
method. Here the
result is
true
since the strings only differ in the case of the first three characters.