What is the output of the following program?
1: public class Main { 2: public static void main(String[] args) { 3: 4: int myValue = 0; 5: int x = 3; 6: while(myValue++ < 3) { 7: int y = (1 + 2 * myValue) % 3; 8: switch(y) { 9: default: 10: case 0: x -= 1; break; 11: case 1: x += 5; 12: } 13: } 14: System.out.println(x); 15: } 16:}
C.
F is incorrect. The code compiles and runs without issue.
The following code adds more println statements to make the execution easy to understand.
public class Main { public static void main(String[] args) { //w w w . jav a 2s .c o m int myValue = 0; int x = 3; while(myValue++ < 3) { int y = (1 + 2 * myValue) % 3; System.out.println(" y:"+y); System.out.println(" myValue:"+myValue); System.out.println(" x:"+x); switch(y) { default: case 0: x -= 1; break; case 1: x += 5; } } System.out.println(x); } }
The code above generates the following result.