Prev Next

Utility methods

What if we want to compare two object instances for equality? What if we want to convert the content of an instance in a convenient form such as String? This section addresses these questions.

equals()

It is often helpful to compare two object instances (of same class) for equality. If p and q are two instances of Point class, it is inappropriate to compare as if (p == q), as this would only compare two references or addresses. We saw this at the end of Encapsulation section. What we need is a method which compares the (relevant) attributes instead of comparing addresses. The equals() method is implemented to determine the equalily. It returns true or false. Illustrated below.

public class Point {
  private int x;  
  private int y;

  public boolean equals(Point q){
    if ( (this.x == q.x) && (this.y == q.y) )
      return true;
    else
      return false;
  }
}

The equals() method can be implemented as appropriate. For example, in your application you would treat 2 instances as same if x values match, you can implement so. In summary,

  Point p = new Point(7,-5);
  Point q = new Point(7,-5);

  if (p == q)    // returns false
  { ... }

  if ( p.equals(q) )   // returns true
  { ... }

One question that might arise is why should we name the method as equals to test the equality? Why can't we give some other name? The equals() method is implemented in the Object class and all classes that we implement extensions to Object class. By using equals() we are overriding its functionality. This will become clear once we discuss inheritance.

Note: C++ has the concept of operator overloading where you can overload the operator such as +, -, ==, etc. Based on the operand types, the appropriate operator would be automatically be invoked. Java doesn't have this feature as the designers of Java language felt this feature is unsafe and can potentially be misused.

2. toString()

Have you tried passing a Point instance to a print statement such as System.out.println(p)? Here p is an instance of Point class. Try it. What does it print?

Wouldn't it be nice if it printed in (x,y) format? It is possible to convert to format of this (or some other) form automatically whenever necessary by implementing 'toString()' method. See the example below. toString() returns a value of String type.

public class Point {
  private int x;  
  private int y;

  public String toString() {
      return "(" + x + "," + y + ")";
  }
}
  Point p = new Point(3,7);
  System.out.println(p);  // p is automatically converted to
  String s = p;           // String format in both cases

Essentially, wherever a String is expected, if you pass a Point instance, it will automatically be converted to (x,y) form.

Note: As you will later learn, toString() and equals() are defined in Object class which we are overridden. This concept will be clear when you learn inheritance.