Integer a = new Integer(3);
Integer b = 3;
System.out.println(a==b);
System.out.println(a.equals(b));
output:
false
true
can someone explain why this example is valid?
Integer a = new Integer(3);
Integer b = 3;
System.out.println(a==b);
System.out.println(a.equals(b));
output:
false
true
can someone explain why this example is valid?
The == operator compares the equality of the objects. Since both objects have their own id/location in the heap memory, this check evaluates to false.
The .equals() method compares the actual values of both objects, in this case 3, which is true.