It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch case basic 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 "switch case basic" Watch "switch case basic" New topic
Author

switch case basic

sameer inamdar
Ranch Hand

Joined: Jul 04, 2005
Posts: 40
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


Dream!!! Set Vision !! Transform Vision to Mission by Actions on Deadlines!.
Osama Hasan
Ranch Hand

Joined: Sep 30, 2002
Posts: 53
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.


SCJP 1.4<br />SCWCD 1.4
sameer inamdar
Ranch Hand

Joined: Jul 04, 2005
Posts: 40
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: switch case basic
 
Similar Threads
Final variables in switch
Swtich Statement
Switch case with static variable
need help on funny switch case logic
changing a final variable