• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

switch & case problem

 
greenhorn
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 .
 
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 ]
 
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:
 
I brought this back from the farm where they grow the tiny ads:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic