• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

switch case basic

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic