Say that itemA
and that ==
itemBitemB
.
How many objects are there?
==
itemC
Just one object (and three reference variables, each referring to it.)
equals()
Method
The equals( String )
method of class String
tests if
two String
s contain the same characters.
The equals( String )
method looks at objects.
It detects equivalence.
The ==
operator detects identity.
For example,
String strA; // first object String strB; // second object strA = new String( "The Gingham Dog" ); strB = new String( "The Gingham Dog" ); // check for equivalence using strA's method if ( strA.equals
( strB ) ) System.out.println( "This WILL print."); // check for equivalence using strB's method if ( strB.equals
( strA ) ) System.out.println( "This WILL print, also."); // check for identity if ( strA==
strB ) System.out.println( "This will NOT print.");
In this example, there are two objects.
Each object has its own identity,
and its own unique reference,
so ==
returns false.
Each object contains equivalent data,
so equals()
returns true.
Both strings have an equals()
method.
You can use either string's method.
You make a photocopy of a sheet of paper. You now have two sheets of paper.
==
the second sheet?equals()
to the second sheet?