What is the output of following piece of code ?

int x = 2;
 switch (x) {
 case 1:System.out.println("1?);
 case 2:
 case 3:System.out.println("3?);
 case 4:
 case 5:System.out.println("5?);
 }
  1. No output

  2. 3 and 5

  3. 1, 3 and 5

  4. 3


Correct Option: B,D
Explanation:

To solve this question, the user needs to understand the concept of switch case statements in Java. The switch statement tests the value of a variable and compares it with multiple cases. If a case matches the value of the variable, then the code inside that case is executed. If no matching cases are found, then the default case is executed.

In the given code, the variable x is initialized to 2. The switch statement checks the value of x, and since it matches the case 2, the code inside that case is executed. Since there are no break statements, the control falls through to the next case, which is 3. Thus, the output will be "3?".

The case for 1 and 5 are not executed because the value of x is not equal to 1 or 5.

Option A is incorrect because there is output from the code. Option B is incorrect because the output is not just 3 and 5. Option C is incorrect because there is no output for 1.

Therefore, the answer is:

The Answer is: D. 3

Find more quizzes: