0
        Integer a1=164;
        Integer a2=164;
        
        System.out.println(a1==a2);
        System.out.println(a1.equals(a2));

        Integer a3=new Integer(164);
        Integer a4=new Integer(164);
        
        System.out.println(a3==a4);
        System.out.println(a3.equals(a4));

This outputs as - 
false
true
false
true

BUT, same code with a slightly different input works in a different way

        Integer a1=64;
        Integer a2=64;
        
        System.out.println(a1==a2);
        System.out.println(a1.equals(a2));

        Integer a3=new Integer(64);
        Integer a4=new Integer(64);
        
        System.out.println(a3==a4);
        System.out.println(a3.equals(a4));

This outputs as -
true
true
false
true

I am sure somewhere the concept of unboxing is playing with me, but I cannot figure this out. Thanks in advance.

P.S. I am not sure if we have a similar question, I did not find one.

  • 1
    https://stackoverflow.com/questions/1700081/why-is-128-128-false-but-127-127-is-true-when-comparing-integer-wrappers-in-ja – Arun Sudhakaran Aug 03 '21 at 08:53
  • read about ```Integer caching``` – Vishal Aug 03 '21 at 09:01
  • `==` compare the reference(where the values are stored) not the values. So always use `.equals()` to compare reference type variable – Abu Saeed Aug 03 '21 at 09:43
  • Thanks everyone, I understood more on this topic by the link provided by @ArunSudhakaran I was asked this in a interview on the name of autoboxing and unboxing, but looks it was more closely related to integer caching which is performed by JVM. – Chitransh Saxena Aug 03 '21 at 15:09

0 Answers0