This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# SCJP question on loop

Aashu Rao
Greenhorn
Posts: 5
Hello friends,

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

I am not getting the reason for this output.

Thanks and regards,
R.Aashu

Animesh Shrivastava
Ranch Hand
Posts: 298
Aashu,
Why have u posted it in this forum?
u should have posted it in SCJP forum

SCJP forum

anyways, ur explanation is here

When i = 0,
1)switch(i++) ----> switch(0), i value changes to 1
u get no matching case

In the next loop u have i value 1, when i++ is done in for loop , u get i = 2.
so,
switch(i++) when i = 2 ----> switch(2) , i value changes to 3.
case 2 is matched, and u get 2 as the first output

In the next loop u have i value 3, when i++ is done in for loop , u get i = 4.
so,
switch(i++) when i = 4 ----> switch(4) , i value changes to 5.
case 2 is matched, and u get 4, 5 as the second output because no break present in the "case 4:"

In the next loop u have i value 5, which doesnt satisfy the for loop condition and for loop quits.

So the final output is
2
4
5

Hope this makes u clear

Aashu Rao
Greenhorn
Posts: 5
Animesh,

Thanks a Lot for the explaination, I got it.
Actually I posted it here bymistake and was searching in SCJP forum.
he he he

Regards,
R.Aashu