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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem in switch statement" Watch "Problem in switch statement" New topic

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;
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

Joined: Jul 22, 2000
Posts: 9059

'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.

"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:
subject: Problem in switch statement
It's not a secret anymore!