Hello
I have a simple confusion.When we use equals() method in Java it means we gonna compare the actual value of that object.But i am not getting correct output in my cases.Does it mean equals() method is use to compare the value of instance variable of classes because instance variables are the state of object.So totally confuse.I have an code below which is giving false output.
vinay kalal wrote:When we use equals() method in Java it means we gonna compare the actual value of that object
Correct, but it actually have to be implemented -- String, Integer, Double, etc. all implements / override the equals() method to correctly compare the values.
It will give "false" as output obviously. because .the default equals() method always compares the references and not the contents. we have to overrride the equals() method as per our requirement.
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = new String("abc");
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
If i run the above code, it returns 3. I think object s1 and s2 references are different , but why it returns true.