Integer i = 127;
Integer j = 127;
System.out.println(i == j);
System.out.println(i.equals(j));
Integer i1 = 128;
Integer j1 = 128;
System.out.println(i1 == j1);
System.out.println(i1.equals(j1));
I don’t understand why its not print “true, true, true, true”. please give answer?
When you use
==, you’re comparing the object instances for equality.The reason that the first two instances are equal is that you created the
Integersby using autoboxing (rather than callingnew Integer(127)), and the Java Language Specification §5.1.7 requires thatIntegersbetween -128 and 127 are cached.Implementations can cache more values than that but are not required to; apparently the JVM you are using does not cache 128. This is the case for Sun Java 6.