-2

I know int range is -2147483648 to +2147483647 but here I'm getting output as true and false. Why? Actually i1 and i2 point to the same object, so output is true. I can understood but i3 and i4 also pointing to same object but I got output as false. Why?

public class MainClass {
    public static void main(String[] args) {
        Integer i1 = 127;
        Integer i2 = 127;
        System.out.println(i1 == i2);
        Integer i3 = 128;
        Integer i4 = 128;
        System.out.println(i3 == i4);
    }
}

the output is

true

false

why output should be like this?

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Mahi
  • 1
  • 2
  • http://stackoverflow.com/questions/10002037/comparing-integer-values-in-java-strange-behavior#10002084 – Victor Jul 02 '15 at 11:45

2 Answers2

2

Because you are using Integer object. For Integer object, values in between -128 to 127 are pooled

Estimate
  • 1,421
  • 1
  • 18
  • 31
0

The problem is the difference between == and equals. == just tests to see if two Integer variables point to the same object, which could be either true or false depending on the implementation of your JVM. equals actually tests to see if they hold the same value. So in this case, you'll want to use equals:

// ...
System.out.println(i1.equals(i2));
// ...
System.out.println(i3.equals(i4));
Sam Estep
  • 12,974
  • 2
  • 37
  • 75