ProgrammingModerateAccenture · Capgemini technical pattern

What is printed?

What is printed?
int x = 5;
x = x++ + ++x;
System.out.print(x);
  1. A. 12
  2. B. 11
  3. C. 7
  4. 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

Exams that ask this topic