With the following:
String a = new String("test");
String b = "test";
System.out.println(a == b); //false
We get false, since String a
is an object, so a
points to a different location in memory than the string literal, b
. I wanted to see how this worked for int
and Integer
:
Integer x = new Integer(5);
int y =5;
System.out.println(x == y); //true
I though that x.equals(y)
would be true, but x == y
would be false as it is in the case with Strings
. I understand that we compare ints
with ==
, but I figured that comparing an int
to an Integer
would be different. Why is this not the case?
I assume that in this case using ==
won't work for comparing references, so how would we do it (not sure if this is practical, but I'd like to know)?