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?

Gain Java Knowledge
2 min readJul 25, 2024

--

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.

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet