Maybe I’ve been working too long on Java without really understanding some of its basics.
I do understand that == is for object reference equality and .equals() is for object value equality.
-
Comparing
Integers:Integer x = 1, y = 1; System.out.println(x == y); // trueWhy? Since object reference equality is used, it should be false since they are both different objects.
-
Comparing
getClass()return values:String s1 = "a", s2 = "b"; System.out.println(s1.getClass() == s2.getClass()); // trueWhy? Again as per above, object reference is used. Both using
getClasswill return separate Class objects.
Did I miss something or is my mind is too tired of coding in Java?
Integer objects
This happens because for values in the
byterange (-128 to +127), java uses cached Integer objects, stored in Integer‘s inner class, IntegerCache. Every time an Integer object is created with value between -128 and +127, the same object will be returned (instead of creating the new object).Conversely, for values outside the
byterange, the comparison isfalse:Class objects
This is true because the class of both objects is
String, and there is only one copy of each class object per JVM (it’s like a singleton). The class object returned fromgetClass()of each String is the same class object (String.class).