Java Reference
In-Depth Information
case 5: lastDay = 31; break;
case 6: lastDay = 30; break;
case 7: lastDay = 31; break;
case 8: lastDay = 31; break;
case 9: lastDay = 30; break;
case 10: lastDay = 31; break;
case 11: lastDay = 30; break;
case 12: lastDay = 31; break;
default: lastDay = 0;
}
This can even be simplified because many of the cases result in the same outcome. As mentioned,
cases are evaluated from top to bottom, and until the execution reaches a break keyword, the state-
ments will continue to be executed. Notice how you can lump the months or cases together to treat
a series of cases identically:
int month = 4; // here 4 represents April
int lastDay;
boolean leapYear = false;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
lastDay = 31; break;
case 2:
if (leapYear == true) {
lastDay = 29;
} else {
lastDay = 28;
} break;
case 4:
case 6:
case 9:
case 11:
lastDay = 30; break;
default: lastDay = 0;
}
Creating a switch
try it out
 To create a switch , follow these steps:
1. Create a new class named SwitchClass , following the same process. You can continue to use the
same Chapter5 project. Create a new class by right-clicking on the src folder in your project.
Select New and then Class.
2. In the Name field, enter the name of your class, SwitchClass , beginning with a capital letter by
Java convention. In the bottom portion of the New Java Class window, there is a section that
Search WWH ::




Custom Search