This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem in switch statement 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 "Problem in switch statement" Watch "Problem in switch statement" New topic
Author

Problem in switch statement

Mr Iftikhar
Ranch Hand

Joined: Oct 12, 2001
Posts: 39
Can any one explain me the following code.
public class Test{
public static void main(String args[]){
char i;
in:
for (i=0;i<5;i++) {
switch(i++) {
case '0': System.out.println("0");
case 1: System.out.println("1"); break in;
case 2: System.out.println("2"); break;
case 3: System.out.println("3"); break;
case 4: System.out.println("4");
case '5': System.out.println("5");
}
}
}}
The output is 2,4,5
Thanks in advanced.

java language
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9043
    
  10

'0' != 0 and '5' != 5
so when i = 0 nothing prints and i is incremented to 1
then i is incremented again by the for loop so i = 2.
when i = 2, "2" prints and i is incremented to 3.
then i is incremented to 4 by the for loop so i = 4.
when i = 4, "4" prints and since there is no break, it falls through to case '5' and prints "5" also.
i is incremented to 5 and we jump out of the for loop because we are only interested in i < 5.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Mr Iftikhar
Ranch Hand

Joined: Oct 12, 2001
Posts: 39
Thanks Marilyn.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in switch statement
 
Similar Threads
Can't understand this tricky for loop question
Cannot understand the output...
Puzzled
need help figuring this out.
SCJP question on loop