What is the purpose of the `switch` statement in Java?
B
To store multiple values
C
To select one of many code blocks to run
D
To define multiple methods
Analysis & Theory
The `switch` statement allows you to execute one block of code among many options based on a variable’s value.
Which types are allowed in a Java `switch` statement (Java 7+)?
A
int, char, String, enum
Analysis & Theory
Java allows `int`, `byte`, `short`, `char`, `String`, and `enum` in `switch` (from Java 7 onwards).
What is the purpose of the `break` statement in a `switch`?
B
To exit the switch block
C
To continue to next case
Analysis & Theory
`break` stops execution within the `switch` block to prevent fall-through.
What happens if `break` is not used in a case?
C
All following cases also execute (fall-through)
Analysis & Theory
Without `break`, Java continues to execute the next cases — this is called fall-through.
What is the output?
```java
int day = 3;
switch(day) {
case 1: System.out.print("Mon"); break;
case 3: System.out.print("Wed"); break;
default: System.out.print("Other");
}```
Analysis & Theory
case 3 matches `day = 3`, so 'Wed' is printed and `break` stops further execution.
Can a `default` block appear in the middle of the cases?
D
Only if no break is used
Analysis & Theory
`default` can be placed anywhere in the switch block, but usually appears last.
Which is the correct way to write a `switch` in Java?
A
switch(x) -> { case 1: break; }
B
switch(x) { case 1: break; }
C
switch x { case 1: break; }
D
switch(x): case 1 { break; }
Analysis & Theory
Correct syntax: `switch(variable) { case value: ... break; }`
What is the output?
```java
char grade = 'B';
switch(grade) {
case 'A': System.out.print("Excellent"); break;
case 'B': System.out.print("Good");
case 'C': System.out.print("Average"); break;
default: System.out.print("Fail");
}```
Analysis & Theory
`case 'B'` matches, but there's no `break`, so 'GoodAverage' is printed (fall-through).
What is the use of the `default` case in a switch?
A
It executes when no `if` condition is met
B
It runs if none of the `case` values match
D
It's used for error handling only
Analysis & Theory
`default` runs when none of the specified cases match the value in `switch`.
Can a `switch` statement be used with a `String` value?
A
Yes, from Java 7 onward
Analysis & Theory
String support in `switch` was introduced in Java 7.