• 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

Switch case with static variable

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

Please read the code given below.

public class FlowControl1 {

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 : 2 1 0 1 def 2

My question is when z = 2, at that time it will go to "case x" as x = 2, but it also goes to the condition "case x-1". I think it should not be. Because "case x-1" will result in 1 and z is not equals to 1. But both code and output is correct. Can anybody please help me?

Thanks.

-Jahnvi
 
lowercase baba
Posts: 13050
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if you don't have a 'break' statement, all the code in all subsequent cases execute.

try reversing the order of your "case x" and "case x-1" and see what happens...
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
switch only does comparison once to find the matching case. It does not compare with other cases when it "falls through".
 
Jahnvi Pathak
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks to both of you Fred and Shin.

This is the very simple rule. I wonder how could I miss it!!

Well, once again thanks.

- Jahnvi

 
What's wrong? Where are you going? Stop! Read this tiny ad:
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