Skip to main content
IBM 
ShopSupportDownloads
IBM HomeProductsConsultingIndustriesNewsAbout IBM
Java Language EssentialsDownload tutorial zip fileEmail this tutorial to a friend
Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
Course Notes
  


Equality page 23 of 37


There is a difference between comparing primitives for equality and comparing two objects for equality. If the value 5 is stored in two different int variables, a comparison of the variables for equality will produce the boolean value true:


public class TestIntComparison {
  public static void main(String[] args) {
  int x = 5, y = 5;
  System.out.println(
    "x == y yields " +
    (x == y));
  }
}

TestIntComparison produces the following output:


D:\>java TestIntComparison
x == y yields true

The equality operator for primitives compares the values.

On the other hand, the equality operator for objects compares the references not the content of the objects. It asks, "do these references refer to the same object?" Consider a trivial version of Dog for illustration purposes that only has a tag number and an age.


class Dog {
  int tag;
  int age;
  public void setTag(int t) {tag=t;}
  public void setAge(int a) {age=a;}
}

If you have two dogs, even if they have the exact same content, they are not equal using the == operator. In the following code fragment, the output will show that a and b are not equal according to this operator.


Dog a = new Dog();
a.setTag(23129);
a.setAge(7);
Dog b = new Dog();
b.setTag(23129);
b.setAge(7);
if ( a==b ) {
  System.out.println("a is equal to b");
}
else {
 System.out.println("a is not equal to b");
}

So, how do you compare two objects by value not by reference? the Java(TM) programming language has a convention that says method equals() defines object value equality. There is a definition of equals() in class Object that is used by default if you do not override it in a subclass. To compare values of dogs a and b, you would rewrite the comparison above as:


if ( a.equals(b) ) {
  System.out.println("a is equals() to b");
}
else {
 System.out.println("a is not equals() to b");
}

In this case, the two dogs will still be found equal unless you override equals() in Dog because Object.equals() mimics the == operator functionality. The definition of equals() in Dog is fairly straightforward:


class Dog {
  int tag;
  int age;
  public void setTag(int t) {tag=t;}
  public void setAge(int a) {age=a;}
  public boolean equals(Object o) {
    Dog d = (Dog)o;
    if ( tag==d.tag && age==d.age ) {
      return true;
    }
    return false;
  }
}

Why does equals() define the argument type as Object instead of Dog? Because you are overriding the definition of equals() from the superclass, Object, you must repeat the same signature. You expect the argument coming in to be another Dog, so you cast the argument to a Dog in order to access its fields.

However, since equals() is defined in Dog, you should check to see that the incoming object is in fact a Dog because somebody could have said:


fido.equals("blort");

The "blort" string is a kind of Object and, hence, would match the equals() signature in Dog. A correct version of equals() is:


public boolean equals(Object o) {
  if ( o instanceof Dog ) {
    Dog d = (Dog)o;
    if ( tag==d.tag && age==d.age ) {
      return true;
    }
  }
  // false if not Dog or contents mismatched
  return false;
}

The instanceof operator asks whether or not o is a kind of Dog (which includes subclasses of Dog).

Comparison of strings introduces a final wrinkle to comparing objects. Is


"abc"=="def"

true or false? This is false because they are physically different objects (obvious because they have different content). However, is the following expression


"abc"=="abc"

true or false? Unfortunately, it depends on the compiler. The compiler is free to optimize those two references to "abc" into one object instead of two objects, in which case the expression is true. However, it does not have to perform this optimization--the expression could be false!

Unless you really want to determine if two strings are physically the same object, always use the equals() method:


boolean b = "abc".equals("def"); // false
boolean c = "abc".equals("abc"); // true

copyright 1996-2000 Magelang Institute dba jGuru


Main menuSection menuGive feedback on this tutorialPrevious panelNext panel
PrivacyLegalContact