# Thread: Understanding the behavior of a switch statement structure without user input

1. Senior Member Join Date
Jul 2013
Location
Wisconsin, USA
Posts
106
Rep Power
0

## Understanding the behavior of a switch statement structure without user input

I'm going through an assessment in my book where one of the questions asks what the output of the following code would be:

Java Code:
```package sam.main;

public class Main{

public static void main(String[] args) {

int count = 0;
int x = 3;
while(count++ < 3) {
System.out.print("1 + (2 * " + count + ") divided by 3 has a remainder of ");
int y = (1 + 2 * count) % 3;//
System.out.println(y);

switch(y) {
default:
case 0: x -= 1; break;
case 1: x += 5;
}
}
System.out.println(x);

}//end of main method
}```
The output of y, and the final value of x is easy enough to find out:

Output:
1 + (2 * 1) divided by 3 has a remainder of 0
1 + (2 * 2) divided by 3 has a remainder of 2
1 + (2 * 3) divided by 3 has a remainder of 1
6

Where I'm completely lost though is the switch statement structure on lines 14 thru 17. What is going on? How do I know which case will be chosen?  Reply With Quote

2. ## Re: Understanding the behavior of a switch statement structure without user input

The tricky part is probably the default case, which has no break, so it just falls over to the case 0: which substracts 1 from x.

So:
- x starts at 3
- first run: y=0, case 0 is hit: x = 3-1 = 2
- second run: y=2, no case, so the default is hit, but it has no break so it falls through to case 0: x = 2 - 1 = 1
- third run: y=1, case 1 is hit: x = 1 + 5 = 6

case 1 has no break either, but since it's the last case it doesn't really matter. Until the day you decide to add case 2, and then it will be broken (again). Make it a habit to end all cases with breaks (or returns).  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•