aspose file tools*
The moose likes Beginning Java and the fly likes Switch statements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Switch statements " Watch "Switch statements " New topic
Author

Switch statements

Adam Preston
Greenhorn

Joined: Mar 04, 2011
Posts: 24
Hi i do not fully understand how a switch statement determines which case to use I have got an example right here and have pointed out the bits which I cannot get my head round... Hope you can help




Hope you can help me, thanks

marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Welcome to the Ranch!

The int value inside the switch parentheses is what it's trying to match. In this case, switch(i) means that it will try to match whatever 'i' is.

It compares this value (i) to the int value following each "case" keyword. So the code following "case 0:" will execute if i is zero.

Maybe you are asking because these look like "indexes" that need to start at zero and increment (0, 1, 2, 3, 4...), but that is not what they are. These are just specific cases to match. So you could have something like this...

Does that help?


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Adam Preston
Greenhorn

Joined: Mar 04, 2011
Posts: 24
ohhhhhhhhhhh i get it now... so if (i) was equal to 124 you would put 'case 124'??

I am assuming in that situation it would probs be easier to use if else if ladder???
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Yes. My example above would be the same as...
Matthew Cox
Greenhorn

Joined: May 25, 2009
Posts: 29
Adam Preston wrote:ohhhhhhhhhhh i get it now... so if (i) was equal to 124 you would put 'case 124'??

I am assuming in that situation it would probs be easier to use if else if ladder???


A switch statement is best to use when there are many cases .. but it is all based upon a singular variable.

If you have multiple variables invovled, that is the time to use an if branch.
Adam Preston
Greenhorn

Joined: Mar 04, 2011
Posts: 24
thanks guys you really helped
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch statements