I was studying basics of java and saw equals() method and wrote this code
public class EqualsTest {
public static void main(String[] args) {
String str = new String("this");
String str2 = new String("this");
Object obj1 = new Object(6);
Object obj2 = new Object(6);
System.out.println(str == str2);
System.out.println(str.equals(str2));
System.out.println(obj1 == obj2);
System.out.println(obj1.equals(obj2));
}
}
and this.
public class Object {
public int num;
public Object(int num) {
this.num = num;
}
}
When I run the code, I get the result saying
false
true
false
false
I could understand why I got first two result. (false and true) '==' operator compares whether str and str2 are referencing the same instance and equals() method compares the actual value inside.
However I could not understood why I got false for both
obj1 == obj2;
obj1.equals(obj2);
I thought since they both have the value 6 with them,
obj1.equals(obj2);
this line should've given the true as a result.
Can someone please explain this?
Thank you.