• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in switch statement

 
Mr Iftikhar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Marilyn de Queiroz
Sheriff
Posts: 9066
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

'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.
 
Mr Iftikhar
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marilyn.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic