About Fall Through Switch Statements In Java :
It is not necessary for every case in the
switch Statement In Java to have a break. Some times we might have a situation where we have the same or similar handling for multiple cases.
Print Alphabets Classification
class AlphabetsClassification
{
public static void main(String arg[])
{
char alphabet = 'A';
switch(alphabet)
{
case 'A':
System.out.println("The alphabet '" + alphabet + "' is in first four letters");
// LINE A
case 'E':
case 'I':
case 'O':
case 'U':
System.out.println("The alphabet '" + alphabet + "' is an vowel");
break;
case 'B':
case 'C':
case 'D':
System.out.println("The alphabet '" + alphabet + "' is in first four letters");
default:
System.out.println("The alphabet '" + alphabet + "' is a consonant");
}
}
}
OUTPUTThe alphabet 'A' is in first four letters
The alphabet 'A' is an vowel
DESCRIPTIONThis program classifies a given alphabet and prints whether it is in the first four letters and whether it is a vowel or a consonant. Here we can observe that we are not using the break
statement for every case
statement. When there is no break
, the execution continues until it encounters a break
or if it reaches the end of the switch statement. That is the reason why when the alphabet is 'A', it prints both The alphabet 'A' is in first four letters and The alphabet 'A' is an vowel. At LINE A
, it simply falls through to the next case
.
THINGS TO TRY
- Change the value of variable
alphabet
to various values like 'B'
, 'E'
, 'K'
etc., and observe the output.
As shown above, when there is no
break
statement, the execution falls through from one case to the next case just below it. Please note that this mistake occurs frequently and it is difficult to identify. So it is
suggested not to use fall through unless it is absolutely required. In case it is required, please
include a comment indicating that it was purposefully carried over to the next
case
.
An example below:
case 'D':
System.out.println("The alphabet '" + alphabet + "' is in first four letters");
// fall through intended
default:
System.out.println("The alphabet '" + alphabet + "' is a consonant");