i came across the following switch statement but couldn't work it out
int i= 1
switch (i) case 1: i++ case 2: i++ case 3: i++ case 4: i++
does it increment after it matches case 1 ? does it contiunue incrementing after each case as there is not break statement ?
One day all greenhorns will run free ...
Joined: Jan 06, 2005
1- Obviously, this code doesn't even compile 2- Sun's docs say: "The break statements are necessary because without them, the case statements fall through. That is, without an explicit break, control will flow sequentially through subsequent case statements."
Here is a small program that shows the syntax of switch. I hope this helps to understand how it works. Please compile and substitute different values for i at the beginning in order to see how the switch operates.
Joined: Aug 07, 2003
Maybe I can guess your next question: Why doesn't Java just do an implicit break after each case? Why make me type it for each case? The answer is that this allows some nice possibilities:
Joined: Aug 23, 2004
Your Code will chk for the first value that matches the case ...It will then execute everything after that till it come to a break or till it exits the block So if u try out a system.out.println() after each case:i++ u will c what i mean .As such i is incremented aneeway. If your first case isn't 1 then it will search for the value which matches i and then execute all other cases therafter including your default case. If there is break aneewhere in between it will as is obvious break out of the switch statement. Cheers