2
public class Question2 {


    public static void main(String[] args) {
        Integer i1 = 1000;
        Integer i2 = 1000;
        Integer i3 = 10;
        Integer i4 = 10;
        System.out.println(i1 == i2);
        System.out.println(i3 == i4);

    }
}

output is

false
true

I understand how the output occurs the problem is why it occurs that way i1 and i2 are 2 objects and their references are different so it outputs false

but i3 and i4 is use the same reference

why it doesn't happen for i1 and i2 why it doesn't use the same reference

Enthu
  • 23
  • 4

1 Answers1

2

Integer uses Integer cache to store the values from -128 to +127. If == operator is used to check for any values between -128 to 127 then it returns true. for other than these values it returns false If you have tried like this,

   Integer i1 = 1000;
    Integer i2 = 1000;
    Integer i3 = new Integer(10);
    Integer i4 = new Integer(10);
    System.out.println(i1 == i2);
    System.out.println(i3 == i4);

Output:

  false
  false
Gouse Mohiddin
  • 420
  • 2
  • 7