wood burning stoves 2.0*
The moose likes Certification Results and the fly likes SCJP question on loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Certification Results
Bookmark "SCJP question on loop" Watch "SCJP question on loop" New topic
Author

SCJP question on loop

Aashu Rao
Greenhorn

Joined: Nov 28, 2004
Posts: 5
Hello friends,

Can anyone please help me with explanation for this code ?


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

Joined: Jul 19, 2004
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
if u have more doubts about this, post the same in the forum whose link i have given above
Aashu Rao
Greenhorn

Joined: Nov 28, 2004
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: SCJP question on loop