Win a copy of Terraform in Action this week in the Cloud 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

switch

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int i=10;
switch (i) {
default :
----
case 10 :
print (10)
case 20:
print (20)
break;
}
this prints 10,20
but how does it do? because i value and 2nd case
statement do not match.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need a "break;" before the "case 20:", otherwise the execution continues right into the next case.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I found a nice example why it is so.
class Switch {
public static void main(String args[]) {
for(int month=1;month<=12;month++) {
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autum";
break;
default:
season = "Bogus Month";
}
System.out.println("Month " +month+" is in the season + ".");
}
}
}

This make sense:
break statement can be effectively use in switch statment.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
and don't forget the default statement can be placed anywhere, it doesn't have to be the last test statement.
"some obscure latin quote here"
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And if the default is not at the bottom as usual that it also falls through if there is no break and everything after it is liable for execution until a break is hit.
They very likely will try this trick in the exam. Mine did!
------------------
"Hierro candente, batir de repente"
reply
    Bookmark Topic Watch Topic
  • New Topic