Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch statements

 
Adam Preston
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Adam Preston
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. My example above would be the same as...
 
Matthew Cox
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys you really helped
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic