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

switch statement

 
Chris Davies
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

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++

default: i++

does it increment after it matches case 1 ? does it contiunue incrementing after each case as there is not break statement ?

cheers

chris
 
Lionel Badiou
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Chris,

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."

Hope that helps,
 
Learning Nuky
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



Nuky.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Nikhilesh Fonseca
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic