java. The output is 2 1 0 def 1 def 1. Can you explain me the following code? pu
ID: 3724977 • Letter: J
Question
java. The output is 2 1 0 def 1 def 1. Can you explain me the following code?
public class Switch2 {
final static short x = 2;
public static int y = 0;
public static void main(String [] args) {
for (int z = 0; z < 4; z++) {
switch (z) {
case x:
System.out.print("0 ");
default:
System.out.print("def ");
case x - 1:
System.out.print("1 ");
break;
case x - 2:
System.out.print("2 ");
}
}
}
}
Explanation / Answer
Answer:
The output is 2 1 0 def 1 def 1
in main method, for loop is running from 0 to 3.
when z is 0, case x-2 will execute so it will print 2
when z is 1, case x -1 will execute so it will print 1
when z is 2, case x and default and case x -1 will execute since each case does not have break statement so it will print 0 def 1
when z is 3, default and case x-1 will execute so it will print def 1
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.