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

Switch Statement

 
Harold Ndou
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 172
Java MySQL Database Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much guys, am now clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic