File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch statement example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "switch statement example" Watch "switch statement example" New topic
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: switch statement example
 
Similar Threads
doubt in kathy sierra question(Flow Control)?
Kathy Sierra doubt
K&B Book for Scjp 6 - Chapter 5 question 8 doubt
Need help to trace java code
Objective 2.1