We bring you solutions to problems in Java.
Common Mistake #2: Missing the ‘break’ Keyword in a Switch-Case Block
These Java issues can be very embarrassing, and sometimes remain undiscovered until run in production. Fallthrough behavior in switch statements is often useful; however, missing a “break” keyword when such behavior is not desired can lead to disastrous results. If you have forgotten to put a “break” in “case 0” in the code example below, the program will write “Zero” followed by “One”, since the control flow inside here will go through the entire “switch” statement until it reaches a “break”.
Example 1:
public class Example {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1:
System.out.println("The number is 1");
break;
case 2:
System.out.println("The number is 2");
break;
case 3:
System.out.println("The number is 3");
break;
default:
System.out.println("The number is not 1, 2, or 3");
break;
}
}
Example 2:
public class Example {
public static void main(String[] args) {
String fruit = "orange";
switch (fruit) {
case "apple":
System.out.println("The fruit is an apple");
break;
case "orange":
case "mandarin":
System.out.println("The fruit is an orange or mandarin");
// Intentionally omitting the 'break' statement to demonstrate a fall-through scenario
case "banana":
System.out.println("The fruit is a banana");
break;
default:
System.out.println("The fruit is not an apple, orange, mandarin, or banana");
break;
}
}
Comments