JavaIntermediate#puzzle#fundamentals

What does this print? Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a == b); System.out.println(c == d);

Integer caches boxed values from -128 to 127 for reuse, so a and b (127) point to the same cached object, making a == b true. 128 is outside the cache range, so c and d are separate objects, making c == d false.

Example
Integer a = 127, b = 127, c = 128, d = 128;
System.out.println(a == b); // true
System.out.println(c == d); // false

Related Questions

1
JavaBeginner#puzzle#operators

What is the output? public class Test { public static void main(String[] args) { System.out.println(10 / 3); System.out.println(10.0 / 3); System.out.println(10 % 3); } }

Open
2
JavaAdvanced#puzzle#oop

What happens when you compile and run this code? class Parent { static void greet() { System.out.println("Parent"); } } class Child extends Parent { static void greet() { System.out.println("Child"); } } Parent p = new Child(); p.greet();

Open
3
JavaIntermediate#puzzle#arrays

What is the output of this array comparison? int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(Arrays.equals(a, b));

Open