Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch statement example

 
Gaurav Gulanjkar
Greenhorn
Posts: 16
Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



unable to figure out the output of the preceding code from k&b book page no-415.
 
Peter Swiss
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it.
thank you to all of you for clearing my doubt's.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic