-1
    public class Test {
    public static void main(String[] args) {
        Integer i=555,j=555;
        System.out.println(i==j); //false
        Integer l=5,n=5;
        System.out.println(l==n); //true
    }
}

Why, Java? How is that even possible?

Tony
  • 3,605
  • 14
  • 52
  • 84

1 Answers1

2

You're comparing the references of two different Integer class instances with the same value, so you must use the equals method (as it must be to compare equality between objects):

Integer i=555,j=555;
System.out.println(i==j); //false
Integer i=555,j=555;
System.out.println(i.equals(j)); //true

But Integer has a pool of Integer object instances for int values between -128 and 127. So when you do

Integer l=5,n=5;
System.out.println(l==n); //true

You receive true since l and n points to the same object reference.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332