📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    What is the output of the following Java code?  

      public class LoopTest {         public static void main(String[] args) {             int x = 0;             while (x < 5) {                 x++;                 if (x == 3) {                     break;                 }             }             System.out.println(x);         }     }
    B 1 Correct Answer Incorrect Answer
    C 2 Correct Answer Incorrect Answer
    D 3 Correct Answer Incorrect Answer
    E 5 Correct Answer Incorrect Answer

    Solution

    Initial: x = 0     Loop 1: x < 5 (0 < 5) is true. x becomes 1. x == 3 (1 == 3) is false.     Loop 2: x < 5 (1 < 5) is true. x becomes 2. x == 3 (2 == 3) is false.     Loop 3: x < 5 (2 < 5) is true. x becomes 3. x == 3 (3 == 3) is true. break executes.     The loop terminates. System.out.println(x) prints 3.

    Practice Next
    More IT Operating System Questions
    ask-question