Member-only story
Why is 1 == 1 is true but Value greater than 127 is false When dealing with Wrapper Classes in Java using == operator?
In this tutorial, we’re going to discuss about the behavior that occurs when we use the ‘==’ operator to compare Wrapper classes.
Let’s look at the example below :
public class TestWrapper {
public static void main(String[] args) {
Integer a = Integer.valueOf(1);
Integer b = 1; // auto-boxing
System.out.println(a == b); // true
}
}
This is a simple example. We created two Integer objects: one using the valueOf()
method provided by the Integer class and the other using autoboxing feature.
Let’s look at the another example but now value should be greater than 127 :
public class TestWrapper {
public static void main(String[] args) {
Integer a = Integer.valueOf(200);
Integer b = 200; // auto-boxing
System.out.println(a == b); // false
}
}
Why is the output different?
The == operator compares memory references. Java caches Integers from -128 to 127, so the first Boolean is indeed comparing the same cached Integer.
In the Second example, value greater than 127 is not cached i.e. 200, which means two different integers are created when putting them into map. Thus, calling == for the second Boolean return false.