Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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: 9692
42
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





 
I knew I would regret that burrito. But this tiny ad has never caused regrets:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic