Integer Objects
Integer x = 1, y = 1; System.out.println(x==y);
This is because for values ββin the byte range (-128 to +127), java uses cached Integer objects stored in the Integer inner class, IntegerCache . Each time an Integer object is created with a value from -128 to +127, the same object will be returned (instead of creating a new object).
Conversely, for values ββoutside the byte range, the comparison is false :
Integer x = 999, y = 999; System.out.println(x==y);
Class objects
String s1 = "a", s2 = "b"; System.out.println(s1.getClass() == s2.getClass());
This is true because the class of both objects is String , and there is only one copy of each class object in the JVM (this is similar to singleton). The class object returned from getClass() each string is the same class object ( String.class ).
source share