• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch case basic

 
sameer inamdar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Switch2 {
final static short x=2;
final static int y =0 ;
public static void main(String [] args)
{
for (int z=0;z<4;z++)
{
switch(z){

case x: System.out.print("0");

case x-1 : System.out.print("1"); break;

default : System.out.print("def");

case x-2 : System.out.print("2");
}
}
}
}


output is 2101def2 can any body explain how . As i din't get the explaination given in the book
 
Osama Hasan
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sameer!

This is what happens here:
On z=0:
The value of z matches with the 4th case label since x-2=0. Thus, 2 is printed . As there are no more statements after this case label, the loop gets re-iterated.

On z=1
The value of z matches with the 2nd case label since x-1=1. Thus 1 is printed. As break is encountered, everything else in the switch block is skipped and the loop is re-iterated.

On z=2
The value of z matches with the 1st case label since x=2. Thus 0 is printed.
As there is no break statement the next case label also gets executed and 1 is printed. On encountering break after the print statement, the loop is re-iterated.

On z=3
The value of z does not match with any of the case label thus the default label is executed which prints 'def'. Again, due to absence of break statement the next case is also executed which prints 2. As this is the last statement, the loop is re-iterated.

Thus the output is: 2101def2

Hope it helps.
 
sameer inamdar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot its very clear now. sometimes its very frustrating if your stuck on some basics and trying to solve.

I would post selected questions from what mocks i am solving hope this will help others to revise.


bye
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic