Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch & case problem

 
pooja jain
greenhorn
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


the above code print output "
1
2
4

my doubt is , why it is printing 2 & 3 . why is the use of then case keyword ( I know by using break keyword we can remove this problem ) but I want to the logic behind it .

thanks in advance .
pooja .
 
Liang Anmian
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you have multiple cases in a switch block, you are only indicating to the JVM where it should BEGIN execution. Once the JVM finds a matching case (meaning the JVM has found the correct entry point), it will just execute all the code below as normal, as though the case keywords are not there.

So to conclude, the "case" keyword is NOT meant for instructing the JVM to perform only this particular snippet of the switch block. It only serves as an entry point of the switch block. Nothing else. If you DO want to force the JVM to perform only this particular code snippet (meaning only statements linked to the matching case), the ONLY way is to use "break".

Anyone, please feel free to correct me if I'm wrong.
[ January 15, 2005: Message edited by: Liang Anmian ]
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to the logic behind it


Java allows you to have several case labels trigger the same action. For instance:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic