Why cant we compare two objects with ==,why we should use only .equals() for objects.

We can compare two Strings with (==) when we assign some string value to the String variable,but if we create an object to that strings and compare eachother we cant use(==) operator ,because we can compare only values with(==) operator but as Objects contains references to that variables we cant use(==) operator,hence .equals() is used on references and (==) is useed on values

Showing Answers 1 - 7 of 7 Answers

m.suresh kumar reddy

  • Oct 19th, 2005
 

the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.ie.when you use == operator for two objects its memory is compared not the value an object is assignedfor example String str1=new String("hello"); String str2=new String("hello");the above two objects are stored in two different memory locations. String str1=new String("hello"); String str2=str1;here two different objects refer to same memory location.so if you use == here it will return true for this. try it and see.i can explain this much only as i am also not well experienced.

  Was this answer useful?  Yes

"==" is called the "Object Reference Equality" & "equals()" method is called the "Object Value equality".

Object1 == Object2;

In above == checks if both reference variables, Object1 & Object2 refers to the same object. If it does returns true, else it returns false.

Object1.equals(Object2);

In this the equals() methods only checks if the values of the two reference variables are same.If it does returns true, else it returns false.

  Was this answer useful?  Yes

paresh

  • Nov 9th, 2005
 

"==" checks only refrences not value .... this is called object refrences operator and equals checks objects ' value

  Was this answer useful?  Yes

Both == and equals() can be used to compare objects but in different aspects== is used to check whether the references are aliases.equals() is used to check for object value equality. equals() method in the object returns true only if the two references compared denote the same object.The equals method in object is overridden to provide the semantics of object value equality.Ex:Strings,Wrapper Classes

  Was this answer useful?  Yes

== operator checks to see if two references are referring to the same location on memory.This is also called shallow comparison.


.equals checks to see if the two objects match each other. This is also known as deep comparison.

  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