⬅ Previous Topic
Java super KeywordNext Topic ⮕
Java synchronized Keyword⬅ Previous Topic
Java super KeywordNext Topic ⮕
Java synchronized Keywordswitch
Keyword in JavaThe switch
keyword in Java is used for decision-making. It's an alternative to writing many if-else-if
statements, and it allows you to test a single expression against multiple possible values. When readability and clarity matter, switch
often makes your code cleaner and more elegant.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default block
}
Here’s what each part means:
int
, char
, String
(since Java 7), or enum
.case
is checked against the value of the expression.int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Another day");
}
Wednesday
Since day
is 3, the third case matches and prints "Wednesday". The break
prevents the next cases from being executed.
int rating = 4;
switch (rating) {
case 5:
System.out.println("Excellent");
case 4:
System.out.println("Good");
case 3:
System.out.println("Fair");
default:
System.out.println("Needs improvement");
}
Good
Fair
Needs improvement
Without break
, the switch statement "falls through" and executes all subsequent cases. That’s why it prints everything starting from case 4
.
String role = "admin";
switch (role) {
case "admin":
System.out.println("Welcome Admin");
break;
case "editor":
System.out.println("Welcome Editor");
break;
default:
System.out.println("Role not recognized");
}
Welcome Admin
Java allows String
types in switch
statements starting with Java 7, making it useful for text-based conditions.
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Well done");
break;
case 'C':
System.out.println("You passed");
break;
default:
System.out.println("Invalid grade");
}
Well done
enum Direction {
NORTH, SOUTH, EAST, WEST
}
Direction dir = Direction.EAST;
switch (dir) {
case NORTH:
System.out.println("You are heading North");
break;
case EAST:
System.out.println("You are heading East");
break;
}
You are heading East
enum
types make switch
more expressive and type-safe, often used in game dev or control systems.
break
unless fall-through is intentional.default
to handle unexpected input.enum
for finite state values to improve readability and safety.String
—it’s case-sensitive.If you need to compare ranges or perform more complex conditions, if-else-if
blocks may be more appropriate.
⬅ Previous Topic
Java super KeywordNext Topic ⮕
Java synchronized KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.