What is the difference between == and equals() in Java?
In Java, the ==
operator is used to compare the references of two objects to see if they point to the same object in memory. The equals()
method, on the other hand, is used to compare the values of two objects to see if they are considered equal.
Here's an example to illustrate the difference:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // prints false
System.out.println(s1.equals(s2)); // prints true
In the example above, s1
and s2
are references to two different objects that have the same value. The ==
operator returns false
because s1
and s2
are references to different objects. The equals()
method, on the other hand, compares the values of the objects and returns true
because both objects have the same value.
It's important to note that the equals()
method is defined in the Object
class, which is the parent class of all Java objects. This means that you can use the equals()
method on any object in Java, but you need to override the method to provide custom behavior for your own classes.