• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to understand default keyword in this scenarios (switch statement)  RSS feed

 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I intentionally placed default before the case label:



output is 8. So I thought default is the first line to execute before case ci.

However when I do this (switched default after case label):


Output is: 8 and default. How come?

Adn also when I do this:


Output is: default. Why does 'default' got printed here?



 
N Sam
Ranch Hand
Posts: 77
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everything is working as expected. When you tag the variable ci as final, it becomes a constant. So, this will pass through compiler, even though your first case has 'ci' for both switch as well as case inside the switch. So, at runtime, the control will jump to case ci. The 'break' will take control flow out of the switch block, even if it is in 'default' case. If there is no 'break' after each case, the control will flow into the next case (or default case). You need to read up online or a book to understand how switch/case works.

 
Chris Barrett
Bartender
Posts: 321
24
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Winston,

Switch statements are much more complex (and powerful) than it's simpler cousin - the if statement. A switch statement evaluates the expression, then executes all statements that follow the matching case label until a break; is executing. If no case labels match the expression, the default label will be executed. Therefore, the default label should always be the final label of the switch, as this is what will be executed if no other case is eligible.

For example:


As the value of ci is 8, case 8 will be executed (printing "This is case 8") and then the switch statement will terminate on the following break; If the value of ci was something other than 8, then only "default" would be printed as no case label was valid.

On the other hand, if my code was:

In that scenario, I did not include break; after case 7, so the processing of statements will continue until a break; is requested:
"This is case 7"
"This is case 8"
.. and now it will break out of the switch.

The Java Tutorials provide a pretty good explanation. For your convenience, the link is: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Cheers!
Chris
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!