Comparing Integer and int with ==

2k Views Asked by At
List<Integer> test = List.of(955, 955);
if (test.get(1) == test.get(0))
...

Above condition results in false

List<Integer> test = List.of(955, 955);
int a = test.get(1);
int b = test.get(0);
if (a == b)
...

The above condition returns true.

Why is that the case? What is the difference between the snippets?

3

There are 3 best solutions below

1
Bill the Lizard On

In one case, you're comparing two Integer object references. In the other case, you're comparing two ints. When using the == operator to compare object references, it will return False if they are not the same object, even if they do wrap the same value.

2
Laura Smith On

First Code Snippet: You are comparing the object reference, meaning the specific object reference that the object is pointing too. In this case you are comparing an Integer which is a wrapper class for int.

Second Code Snippet: You are comparing the an 'int' to another 'int'.

Example:

Think about it this way: if two people had the name John, in the first scenario we are comparing the people named John, whereas in the second scenario we are comparing the name John only. I hope that helped!

0
Akif Hadziabdic On
  • In the first example, you are comparing references. In your example, you have two different objects with different references and the same values.

  • In the second example, you are using automatic unboxing which creates new integers in stack memory, and integer comparison which works what you expect. Automatic unboxing can produce NullPointerException in case of null.