ProgrammingModerateAccenture · Capgemini technical pattern
What is printed?
What is printed?
int x = 5; x = x++ + ++x; System.out.print(x);
- A. 12
- B. 11
- C. 7
- D. 5
Correct answer: A. 12
Java evaluates left to right: x++ yields 5 (x becomes 6), then ++x makes x 7 and yields 7; 5 + 7 = 12 is assigned, overwriting the increments. Reading ++x as 6 gives 11, letting the increments win gives 7, and 5 assumes the assignment keeps the old value.
More OOP with C++ and Java questions
- What is printed? cpp class A { public: int x; A(int v) : x(v) {} }; int main() { A a(5); A b = a; b.x = 9; cout << a.x << b.x; }
- Which line fails to compile? java abstract class Shape { abstract double area(); } class Sq extends Shape { double area() { return 4; } }…
- What is printed? java class K { K() { this(5); System.out.print("A"); } K(int x) { System.out.print("B" + x); } } // in main: new K();
- Which line fails to compile? java final int[] arr = {1, 2, 3}; arr[0] = 10; // L1 arr = new int[3]; // L2 System.out.print(arr[0]); // L3
- What is printed? java class P { static int c = 0; P() { c++; } } class Q extends P { Q() { c += 10; } } // in main: new P(); new Q(); new…
- What is printed? java class A { int x = 10; A() { x = 20; } { x = 30; } } // in main: System.out.print(new A().x);