ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        Integer c = 200;
        Integer d = 200;
        System.out.println((a == b) + " " + (c == d));
    }
}
  1. A. true true
  2. B. false false
  3. C. true false
  4. D. false true

Correct answer: C. true false

Autoboxing uses Integer.valueOf, which caches boxed values in the range -128 to 127. 127 is within that range, so a and b refer to the same cached object (a == b is true). 200 is outside the cache range, so c and d are distinct boxed objects (c == d is false).

More OOP with C++ and Java questions

Exams that ask this topic