-1

Why Integer class return false even if value two Integer variables are same. This happens only when value is more than 127.

    Integer a = 300;
    Integer b = 300;
    System.out.println(a==b);

The above code prints false. The value of variables a and b are same then why this prints false.

    Integer a = 127;
    Integer b = 127;
    System.out.println(a==b);

This code will print true. Can anybody please explain me why java behave like this.

Thanks

Prithvipal Singh
  • 511
  • 4
  • 9
  • 23

1 Answers1

3

That's because the values under 127 being cached and using same location of storage for performance reasons in micro level. That's the reason for true in second case.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307