ProgrammingModerateTCS NQT · Infosys
What does this Java code print? Integer a = 127, b = 127, c = 128, d = 128; System.out.println((a == b) + " " + (c == d) + " " + c.equals(d));
- A. true false true
- B. true true true
- C. false false true
- D. true false false
Correct answer: A. true false true
Autoboxing uses Integer.valueOf, and the language guarantees a cache for values -128 to 127, so a == b is true. 128 creates two separate objects, so c == d is false, while equals compares the values and is true.
More OOP with C++ and Java questions
- What does this Java code print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get() {…
- What does this Java program print? class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } }…
- What does this Java program print? static int f() { int x = 1; try { return x; } finally { x = 3; } } static int g() { try { throw new…
- What does this C++ program print? struct B { B() { f(); } virtual void f() { std::cout << "B"; } }; struct D : B { D() { f(); } void f()…
- What does this C++ program print? struct B { virtual void f(int x = 1) { std::cout << "B" << x; } }; struct D : B { void f(int x = 2)…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }…