Thursday 1 December 2011

The equals() method

We can use the == operator to compare the values of primitive variables and determine if they are equal. However, if object reference variables are compared using the == operator, it returns true only if the reference variables are referring to the same object. To check for the equality of two objects, the Object class provides the equals(Object obj) method, which can be overridden to return true for logically equal objects. The default implementation of the equals() method in the Object class returns true only if an object is compared to itself -- that is, it behaves similarly to the == operator. Classes like String and Boolean have overridden the equals() method, while StringBuffer has not. For instance:

String s1 = "abc";
String s2 = new String("abc");
if (s1 == s2)                        // returns false


System.out.println("Same Object Reference");


if (s1.equals(s2))               // returns true


System.out.println("Equal Objects");   // prints "Equal Objects"



Passing variables into methods


If the variable passed is a primitive, only a copy of the variable is actually passed to the method. So modifying the variable within the method has no effect on the actual variable.

When you pass an object variable into a method, a copy of the reference variable is actually passed. In this case, both variables refer to the same object. If the object is modified inside the method, the change is visible in the original variable also. Though the called method can change the object referred by the variable passed, it cannot change the actual variable in the calling method. In other words, you cannot reassign the original reference variable to some other value. For instance:

class MyClass
{


int a = 3;
void setNum(int a)
{


this.a = a;


}
int getNum()
{


return a;


}


}


class Test
{


static void change(MyClass x)
{


x.setNum(9);


}
public static void main(String args[])
{


MyClass my = new MyClass();
change(my);
System.out.println(my.getNum());     // Prints 9


}


}


In the above example, you can see that changing the object referred to by x changes the same object referred to by my.

Be clear about how equality is tested with the == operator and the significance of the equals() method for the objects. Also, remember that objects are passed by a copy of the reference value, while primitives are passed by a copy of the primitive's value.

2 comments: