0

I was trying to see what is true table for some Type in Java.

And i cant understand way top one returns true and one below false ?

public class CompareTypes{

    public static void main(String[] args){

        // -------------------------------------
        Integer AA = 12;
        Integer BB = 12;
        System.out.println( AA == BB ); // true

        // -------------------------------------
        Integer a = 128;
        Integer b = 128;
        System.out.println( a == b ); // false


    }

}
ch3ll0v3k
  • 336
  • 3
  • 9

1 Answers1

1

You're seeing an artifact of autoboxing.

Integer objects have different object id's, which mean that that two different Integer objects will be false for ==. However, the valueOf method caches the first 127 values of the Integer object. When you create an Integer between -128 and +127, via its valueOf static factory then you get the exact same object. When you create one with a value >= 128 then you get a whole new object every time, with a different id and so not responding intuitively to the == call.

Autoboxing uses the valueOf method to do the autoboxing, which is why the object references created as Integer objects from int literals less than 128 work. The lines creating two Integer objects of value 128, however, create two different objects.

The moral of the story is

  • try to use .equals() for value types
  • beware of mixing up literal types and boxed types.

https://blogs.oracle.com/darcy/entry/boxing_and_caches_integer_valueof

sisyphus
  • 6,174
  • 1
  • 25
  • 35