Switch Statement in Java
Introduction:
A switch statement simplifies decision-making by executing a block of code based on a single expression. Unlike if...else
, it makes the code more structured and readable.
1. Switch Statement
byte, short, char, int
), String
, and some wrapper classes (Character, Byte, Short, Integer
).Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default block
}
Output:
100 / 10 = 10
, so case 10
executes.Example 2: No Matching Case :
Output:
Other Number
100 / 4 = 25
doesn’t match any case, the default case runs.Example 3: Optional Default Case :
class Main {
public static void main(String[] args) {
int remainder = 4 % 3;
switch (remainder) {
case 0:
System.out.println("Even Number");
break;
case 1:
System.out.println("Odd Number");
break;
}
}
}
Output :
Odd NumberHere,
4 % 3 = 1
, so case 1
executes. The default case is optional.2. Break in Switch-Case :
The break statement stops execution after a matching case. If omitted, execution falls through and continues with subsequent cases.
Example 1: Missing Break (Fall-through Behavior) :
Output:
break
is missing, execution continues through all cases.Example 2: No Break in Any Case :
Output:
Here, 2 * 2 = 4
, so case 4
executes. Since break
is missing, execution continues to case 6 and default case.
Summary
- Switch statements evaluate an expression and match it with predefined cases.
- Work with primitive types, String, and some wrapper classes.
- Break statements prevent fall-through execution. If missing, all subsequent cases run.