Win a copy of High Performance Python for Data Analytics this week in the Python 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

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: 12955
65
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

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic