This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a swith/case question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a swith/case question" Watch "a swith/case question" New topic

a swith/case question

Shiao Kung Chux

Joined: Jan 26, 2006
Posts: 25
1. int i=1, j=0;
3. switch(i){ 2:
5. j+=6;
7. case 4:
8. j+=1;
10. default:
11. j +=2;
13. case 0:
14. j +=4;

What is the value of j at line 16?
A. 0
B. 1
C. 2
D. 4
E. 6

why the answer is E?

while everyone is busy , i am free
Tilo Hemp
Ranch Hand

Joined: Nov 21, 2005
Posts: 91
- no case matches 1, so default case is executed
- at the end of the default case, no break statement is given, so case 0 is executed also ("fall through")

Shiao Kung Chux

Joined: Jan 26, 2006
Posts: 25
Arnab Sadhukhan

Joined: Sep 09, 2005
Posts: 6
The answer is 6.
First the default case will be executed, and after default the last case will be executed.
Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
Hi Shiao,

Keep in mind that when using a switch statement, the case option is just an entry point for processing. So if after enter the entry point the program doesn't find any break instruction, the program will still process everything it found.

"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
I agree. Here's the link:
subject: a swith/case question
It's not a secret anymore!