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.
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.