Thursday, April 11, 2013

Difference between == and equals()


== operator compares the object reference and returns true if the reference of both the objects are same. i.e. Both are same object.
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
Integer i3 =  i1;
System.out.println(i1==i2);
System.out.println(i1==i3);

O/P:-
false
true

equals() method of Object class is same as == operator. i.e. it compares the reference. But we can override it to write our business logic and return TRUE or FALSE accordingly. For example String class and Integer class have overridden equals methods to return true if the value of objects are equal.
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
             
System.out.println(i1==i2);
System.out.println(i1.equals(i2));

O/P:-
false
true

No comments:

Post a Comment