Given the code fragment:
String color = “Red”;
switch(color) {
case “Red”:
System.out.println(“Found Red”);
case “Blue”:
System.out.println(“Found Blue”);
break;
case “White”:
System.out.println(“Found White”);
break;
default:
System.out.println(“Found Default”);
}
What is the result?
A.
Found Red
B.
Found Red
Found Blue
C.
Found Red
Found Blue
Found White
D.
Found Red
Found Blue
Found White
Found Default
Explanation:
As there is no break statement after the case “Red” statement the case Blue statement will run as well.
Note: The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
“B”
break – jumps out of the switch()-case
The Answer is B.
Also note that the default case can appear anywhere in the switch statement. It doesn’t have to be at the end. If the default case is at the end, there is no need to have a break; statement for it.
Additionally, a Java switch statement works with the byte, short, char, and int primitive data types. It also works with enumerated types (enum), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer.
enums do not appear on this exam.