Equality of Objects, cont'd

Recall that objects are typically handled by references to the objects.

 

When references are compared using == in Java, the result is based on the literal value of the reference, not the Object to which the reference refers.

 

(The same is true for pointers in C/C++.)

 

Two different String objects may have exactly the same characters, but still not compare true with == because the references are different.

 

The method equals must be used instead to compare two strings for content:

String s1, s2;
....
if( s1.equals(s2) )
  {
  }

and not

String s1, s2;
....
if( s1 == s2 )
  {
  }

Exercise: Rewrite the member method to work properly for strings.

Next Slide Previous Slide Contents