• 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

need help on funny switch case logic

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



I found this code on a mock test,and I'm unable to find the logic behind it. Can someone please explain it to me.
Thanks a lot if help arrives,
cheers
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Someswar, welcome to javaranch

Well here we have a rule that if you post a question from a mock exam, you have tell the source of the question. So please tell us the source of the question so that we can help you.

Also this code seems normal to me. What is it that you don't understand?? Default can be put before case clause, x-1 and x-2 are allowed as case expression as x is a compile time constant. Is there anything else that is confusing you??
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

First you have to know that you can use compilation time constants in a case evaluation, now, I recomended to use a pencil and a piece of paper and write this:

Since x value is 2

switch(z)
{
case x:System.out.println("0"); case 2 print 0
case x-1:System.out.println("1");break; case 1 print 1 break;
default:System.out.println("def"); default def
case x-2:System.out.println("2"); case 0 print 2

}

So now is easier to match cases, remember, if you don't see the break, you fall throug the cases:


z=0, print 2
z=1, print 1
z=2, print 0 (no break) and print 1 (break).

So since z goes from 0 to 2 the output is (Your Case For loop from 0 to z<3):

2 1 0 1

if z would go from 0 to 3 the Output will be (For loop from 0 to z<=3)

2 1 0 1 def 2





 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic