OCA Java SE 8 Mock Exam - OCA Mock Question 33
Question
What is the output of the following code?
public class Main {
public static void main(String args[]) {
int a = 0;
while (a == a++) {
a++;
System.out.println(a);
}
}
}
- The while loop won't execute; nothing will be printed.
- The while statement will loop forever, printing all numbers, starting from 1.
- The while statement will loop forever, printing all even numbers, starting from 0.
- The while statement will loop forever, printing all even numbers, starting from 2.
- The while statement will loop forever, printing all odd numbers, starting from 1.
- The while statement will loop forever, printing all odd numbers, starting from 3.
Answer
Note
The while loop will execute indefinitely because the condition a == a++
will always evaluate to true.
The postfix unary operator will increment the value of the
variable a after it's used in the comparison expression.
a++ within the loop body will
increment the value of a by 1.
Hence, the value of a increments by 2 in a single loop.