Question:
Integer valor = 127;
Integer valor2 = 127;
System.out.printIn(valor == valor2);
Output: true
Integer valor = 128;
Integer valor2 = 128;
System.out.printIn(valor == valor2);
Output: false
Why does it happen?
Answer:
The Integer class is part of the Wrapper class package and not a primitive data type like int
. What we call a Wrapper is a class that represents a primitive type. For example the wrapper of int
is Integer
. Note that the Wrapper starts with a capital letter, it follows the same nomenclature as any other class, as it is also one.
For this reason the ==
operator is not recommended for comparing values of the Integer
class. For that we use another comparator, the equals
.
Example 1:
Integer valor = 127;
Integer valor2 = 127;
System.out.println(valor == valor2); // Saída: true
System.out.println(Objects.equals(valor, valor2)); // Saída: true
Note that in both cases it returns true.
Now let's look at another example:
Integer valor3 = 128;
Integer valor4 = 128;
System.out.println(valor3 == valor4); // Saída: false
System.out.println(Objects.equals(valor3, valor4)); // Saída: true
But the question is, why does the ==
work for Integer
127 and not Integer
128?
The answer is simple: The JVM is caching integer values. So the ==
only works for numbers between -128 and 127. This cache is mentioned in the documentation for the valueOf
method, which the first impression is called internally when autoboxing , a feature that automatically converts primitive types to their wrapper equivalent.
Note: If you used the primitive data type int
a simple comparison using the ==
comparator would work.
int valorTeste = 128;
int valorTeste2 = 128;
System.out.println(valorTeste == valorTeste2); // Saída: true