- What is switch-case in Java?
- Syntax of switch-case
- Let’s break this down
- Supported Data Types in switch-case
- Example 1: switch-case with int
- Example 2: switch-case with String
- What happens without break? (Fall-through behavior)
- Example:
- Why use break?
- Using default case
- Nested switch-case
- Step-by-Step Explanation
- Things to remember about switch case
- Lets see Calculator Example for better understanding
- Short explanation of the calculator program
- Test Your Knowledge
- 1. What happens if break is not used in a switch-case?
- 2. Can we use float in a switch expression?
- 3. Which version of Java introduced String in switch?
- 4. Can we use variables inside case labels?
- 5. Is default mandatory in switch-case?
- Practice Set
- Conclusion
When you’re learning Java programming, you’ll often face situations where you need to make decisions based on multiple possible values. You may have already learned about the if-else ladder. But when you have to compare one variable with multiple values, Java gives you a more readable and organized way to handle this: switch-case.
In this tutorial, we’ll break down everything you need to know about switch-case in Java with examples and clear explanations.
What is switch-case in Java?
The switch-case statement in Java is a control flow structure that helps you make decisions based on the value of a single variable. Instead of writing multiple if-else conditions, you can use switch to test the variable against a list of possible values, known as cases.
When a match is found, the corresponding block of code runs. This makes the code easier to read and manage, especially when you have many conditions to check. If none of the cases match, the default block (if provided) is executed.
It is often used as an alternative to a long if-else-if ladder, especially when comparing the same variable against different values.
Syntax of switch-case
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default code block
}
Let’s break this down
expression: A variable or expression that returns a value. It is compared against each case.case value:: A possible value the expression may match.break;: Used to exit the switch block. If omitted, execution will “fall through” to the next case.default:: Code that runs if no case matches. It is optional.
Supported Data Types in switch-case
Java supports the following data types in switch:
int,byte,short,charenumtypesString(Java 7 and later)- Wrapper classes of primitive types like
Integer,Character, etc.
Example 1: switch-case with int
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Tuesday
In the above example, day is 3, so the case with value 3 gets executed.
Example 2: switch-case with String
public class StringSwitch {
public static void main(String[] args) {
String fruit = "Apple";
switch (fruit) {
case "Apple":
System.out.println("Red fruit");
break;
case "Banana":
System.out.println("Yellow fruit");
break;
default:
System.out.println("Unknown fruit");
}
}
}
Output:
Red fruit
String matching is case-sensitive, so "apple" would not match "Apple".
What happens without break? (Fall-through behavior)
If you don’t use break, the program continues to execute the next case statements.
Example:
int number = 2;
switch (number) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
}
Output:
Two
Three
For the given input value 2 in number variable, The code matched with case 2, but also executed case 3 because there were no break statements.
Why use break?
The break statement is used to prevent fall-through. Once a matching case is found and executed, break helps the program exit the switch block, avoiding the execution of unintended cases.
Using default case
The default case is used as a fallback option when none of the defined cases match.
In the below example, for the grade “F” no switch case will match. So, It will execute the default case.
String grade = "F";
switch (grade) {
case "A":
System.out.println("Excellent!");
break;
case "B":
System.out.println("Very Good!");
break;
default:
System.out.println("Work Harder!");
}
Output:
Work Harder!
Nested switch-case
A nested switch-case means using one switch statement inside another. This is helpful when you need to make a second-level decision that depends on the first-level decision. However, this structure should be used only when truly necessary, as it can make your code harder to read.
It’s not commonly recommended unless the logic is really dependent.
int outer = 1;
int inner = 2;
switch (outer) {
case 1:
switch (inner) {
case 2:
System.out.println("Inner matched 2");
break;
}
break;
}
Output:
matched 2
Step-by-Step Explanation
1. Variable Declarations:
int outer = 1;
int inner = 2;
outerholds the value1innerholds the value2
2. Outer switch:
switch (outer)
- The outer switch checks the value of the
outervariable. - Since
outer = 1, it matches this:
case 1:
3. Inner switch:
Inside the outer case block, there’s another switch:
switch (inner)
- It now checks the value of
inner, which is2. - It finds a matching case:
case 2:
System.out.println("Inner matched 2");
break;
4. Execution Result:
Since both outer == 1 and inner == 2, the message:
Inner matched 2 is printed.
Things to remember about switch case
| Rule | Explanation |
|---|---|
| Only certain data types are allowed | int, char, String, etc. |
| Cases must be constants or literals | You cannot use variables in case labels |
| No duplicate cases allowed | Each case value must be unique |
default is optional | But useful for unmatched cases |
| Fall-through can happen | Without break, execution moves to next case |
Lets see Calculator Example for better understanding
public class Calculator {
public static void main(String[] args) {
char operator = '+';
int a = 10, b = 5;
switch (operator) {
case '+':
System.out.println("Sum: " + (a + b));
break;
case '-':
System.out.println("Difference: " + (a - b));
break;
case '*':
System.out.println("Product: " + (a * b));
break;
case '/':
System.out.println("Quotient: " + (a / b));
break;
default:
System.out.println("Invalid Operator");
}
}
}
Output
Since operator = '+', the output will be:
Sum: 15
Short explanation of the calculator program
This Java program is a simple calculator using switch-case.
It uses an operator (+, -, *, or /) to perform a specific operation on two numbers a = 10 and b = 5.
- If the operator is
'+', it adds the numbers and prints the sum. - If it’s
'-', it prints the difference. - If it’s
'*', it prints the product. - If it’s
'/', it prints the quotient. - If the operator doesn’t match any case, it prints “Invalid Operator”.
Since the operator is '+', the output is:
Sum: 15
The break statements prevent unwanted case fall-through.
Test Your Knowledge
1. What happens if break is not used in a switch-case?
If break is not used, execution will continue to the next case even if it doesn’t match. This is called fall-through behavior.
2. Can we use float in a switch expression?
❌ No, float, double, long, and boolean cannot be used in a switch expression.
Only int, char, byte, short, enum, and String (Java 7+) are allowed.
3. Which version of Java introduced String in switch?
Java 7 introduced support for using String in switch expressions.
4. Can we use variables inside case labels?
❌ No, case labels must be constant values. You cannot use variables or expressions.
5. Is default mandatory in switch-case?
❌ No, the default case is optional, but it’s good practice to include it to handle unexpected values.
Practice Set
- Write a program to print the name of the month based on an integer input (1 to 12).
- Create a switch-case program to simulate a simple menu system (1. View, 2. Edit, 3. Delete, 4. Exit).
- Write a switch-case based calculator program (Add, Subtract, Multiply, Divide).
- Create a program using switch-case to check grade remarks (
A,B,C,D,F).
Conclusion
The switch-case in Java is a great alternative to complex if-else-if statements when you’re comparing the same variable with many values. It’s more readable, easier to debug, and often performs better. Understanding how it works including the use of break, default, and valid data types will help you write cleaner, more efficient code.
So next time you’re comparing multiple values, think switch-case!