aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch & case problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "switch & case problem" Watch "switch & case problem" New topic
Author

switch & case problem

pooja jain
greenhorn
Ranch Hand

Joined: Jan 12, 2005
Posts: 213


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 .


:d
Liang Anmian
Ranch Hand

Joined: Jun 25, 2004
Posts: 119
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 ]

Current Status:<br /> <br />SCJP 1.4<br />SCJD (in progress)
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
I want to the logic behind it


Java allows you to have several case labels trigger the same action. For instance:


Mike Gershman
SCJP 1.4, SCWCD in process
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: switch & case problem