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); 
                 } 
             } 
         } 
  1. The while loop won't execute; nothing will be printed.
  2. The while statement will loop forever, printing all numbers, starting from 1.
  3. The while statement will loop forever, printing all even numbers, starting from 0.
  4. The while statement will loop forever, printing all even numbers, starting from 2.
  5. The while statement will loop forever, printing all odd numbers, starting from 1.
  6. The while statement will loop forever, printing all odd numbers, starting from 3.




Answer



D

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.