File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "switch" Watch "switch" New topic
Author

switch

josephine chen
Ranch Hand

Joined: Oct 29, 2002
Posts: 216
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.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18641
You need a "break;" before the "case 20:", otherwise the execution continues right into the next case.


"I'm not back." - Bill Harding, Twister
RajeshParab
Greenhorn

Joined: Feb 08, 2000
Posts: 14
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.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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"
Gilbert Baron
Greenhorn

Joined: Feb 12, 2000
Posts: 23
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"


"Hierro candente, batir de repente"
 
 
subject: switch
 
developer file tools

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture