| Author |
switch statement example
|
Gaurav Gulanjkar
Greenhorn
Joined: Feb 10, 2011
Posts: 16
|
|
unable to figure out the output of the preceding code from k&b book page no-415.
|
 |
Peter Swiss
Greenhorn
Joined: Mar 03, 2011
Posts: 23
|
|
Class Ebb is loaded - static variable x is initialized to 7. static intializer block runs , x is incremented to 8
main method begins:
for loop:
1st iteration: x becomes 9, switch goes to case 9, prints 9, fall-thru to 10, prints 10 and break
2nd iteration: x becomes 10, switch goes to case 10, prints 10 and break
3rd iteration: x becomes 11, switch goes to default, prints d, fall-thru to 13, prints 13
You get "9 10 10 d 13"
Option D is correct
Peter Swiss
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
|
notable point here is that the break inside switch dont interrupt the for loop; only break outside the switch has effect on for loop.
|
 |
Gaurav Gulanjkar
Greenhorn
Joined: Feb 10, 2011
Posts: 16
|
|
|
but how is x incremented to 9 as the operator used is post increment operator and it says that first use and then increment at first iteration.
|
 |
Peter Swiss
Greenhorn
Joined: Mar 03, 2011
Posts: 23
|
|
Gaurav Gulanjkar wrote: it says that first use and then increment at first iteration.
the statement is x++;
you use x then increment. The scope of "use" is only for the current statement.
So you use it - it is 8
you increment it - it is 9
|
 |
Gaurav Gulanjkar
Greenhorn
Joined: Feb 10, 2011
Posts: 16
|
|
I got it.
thank you to all of you for clearing my doubt's.
|
 |
 |
|
|
subject: switch statement example
|
|
|