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
posted
0
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
posted
0
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
posted
0
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
posted
0
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"