-4

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)?

Steve P.
  • 14,489
  • 8
  • 42
  • 72

1 Answers1

3

Because of boxing and unboxing in java

Converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Autoboxing/unboxing is a pure convenience feature that allows you to assign values of a primitive type a reference of a wrapper class and vice versa, with the compiler automatically adding the code to convert between the two.

Boxing and unBoxing and SEE HERE ALSO

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151