What is the difference between equals and ==

Showing Answers 1 - 3 of 3 Answers

Scott

  • May 12th, 2005
 

The == comparator simply checks to see that two primitives are equivelent by virtue of memory location. 
The equals( ) method will actually check to see that the values of the two objects are equivelent.  
A good rule of thumb is to always use the equals( ) method when comparing objects and == when comparing primitives. 
 
Example: 
String h = "Hello"; 
String h1 = "Hello"; 
if ( h == h1 ) 

System.out.println( "The two are equal" ); 

else  

System.out.println( "They are not equal" ); 

 
Of course, they are equal. But now: 
 
String h = new String( "Hello" ); 
String h1 = new String ( "Hello" ); 
if ( h == h1 ) 

System.out.println( "The two are equal" ); 

else  

System.out.println( "They are not equal" ); 

 
They are not. You would have to use the .equals( ) method to test for equivalence: 
 
if ( h.equals( h1 ) )

dpk

  • Sep 9th, 2005
 

== checks whether two types points to same object. equals() checks whether the stored value is same in two.

  Was this answer useful?  Yes

nakt

  • Nov 18th, 2005
 

The eauals method of Object class checks whether the objects refeences by the variables is same or not . It does not check the contents of the object . Therefor if the contents are to be checked for the behaviour of equals method the inherited class has to overload the equals method . As most of the java classes overload the equals method, we get the content based equality. In user defined class , you have to do that ..

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions