aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Switch Statement" Watch "Switch Statement" New topic
Author

Switch Statement

Harold Ndou
Ranch Hand

Joined: May 19, 2013
Posts: 34


Hi everyone am struglling to understand some part of this code especially this line:

case 10: { s+= "10 "; break; }

The result of above code is: 9 10 10 d 13
I dont understand when it prints 10 10 in succession. I will appreciate your assistance.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11318
    
  16

Your code doesn't even come close to compiling, so it would by pointless to try and figure out why you got the output you did.

Please post the full and complete code you are running, and please UseCodeTags when you do.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4392
    
    8

Once you've done that...do you understand the idea of "falling through" in a switch statement? So, what happens if a case block doesn't have a break statement? Because that's what explains the output here.
Harold Ndou
Ranch Hand

Joined: May 19, 2013
Posts: 34
Hi guys
Thanks for advice, i now put my code inside code tags, please can you explain to me the fall- trough and break concepts so i can understand the result
Ashish Dutt
Ranch Hand

Joined: Apr 12, 2013
Posts: 172

In a switch case, if the condition case does not have the break keyword then the code will simply Fall through so for example

The above code will output Ten Three Four No Match ... why so, because of the absence of a break keyword at case 10, so the code just "fell through" executing all the statements until it encountered a break keyword.
Hope this helps.


Still a beginner at crafting quality coding but have the zeal to learn more. Your help would be appreciated.
My Blog on Learning Analytics
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11318
    
  16

You can think of the "case <whatever>" as nothing more than labels. So when the "switch (x)" line is reached, the jvm decides what line to jump to. It then starts execution from that point, ignoring an more labels in the current switch statement. The only thing that would matter would be hitting a break statement, which says "now skip down to the first statement outside this switch block.
Harold Ndou
Ranch Hand

Joined: May 19, 2013
Posts: 34
Thanks so much guys, am now clear.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch Statement