Java is a high-level, class-based, object-oriented programming language. In Java, switch statements provide a way to execute one block of source code, among many, based on the value of an expression. It is an alternative to multiple ‘if-else’ statements.
If there is a match, the associated block of code is executed. Switch case in Java is fall-through, which means it executes all the cases after the first match if a break statement is not encountered.
What is Switch Statement?
A switch statement in Java is a control flow statement that allows the execution of one block of source code among many based on the value of an expression. It provides a more efficient and readable way to handle multiple possible values for a variable, compared to using multiple ‘if-else’ statements. The ‘switch’ statement evaluates the expression provided and then matches its result with one of the ‘case’ labels defined within the ‘switch’ block.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Syntax of Switch Statement
The syntax of a switch statement in Java is as follows.
switch (expression) {
case value1:
// Code block
break;
case value2:
// Code block
break;
// more cases
default:
// Default code block
}
The following program demonstrates the switch statement.
Program
class Main{
public static void main(String args[]){
System.out.println("Neeraj Kumar ") ;
int number = 2 ;
switch(number) {
case 1: System.out.println("Number is One") ;
break ;
case 2: System.out.println("Number is Second") ;
break ;
case 3: System.out.println("Number is third") ;
break ;
case 4: System.out.println("Number is fourth") ;
break ;
case 5: System.out.println("Number is five") ;
break ;
default : System.out.println("Number is Invalid") ;
}
}
}
Output
Neeraj Kumar
Number is Second
Some Important Rules for Java Switch Statements
Here are some important rules for using switch statements in Java language.
The case value must be constants or literals of the same type as the switch expression.
Switch does not allow duplicate case values.
The break statement is used to exit from the switch block. The break statement is optional, but It is recommended.
The default case is also optional. It executes if no cases match the switch expression.
A Switch statement allows you to execute different source code blocks depending on the value of a variable or expression. Here are basic important aspects of a switch statement.
Multiple Case Labels: We can have multiple ‘case’ labels within a ‘switch’ statement. Each ‘case’ corresponds to a specific value the ‘switch’ expression might take.
Default Case: The ‘default’ label is optional but recommended. It provides a fallback option when none of the ‘case’ labels matches the ‘switch’ expression.
Expression Support: Since Java 12, ‘switch’ supports expression syntax, allowing it to return a value. This new syntax makes ‘switch’ concise and expressive.
The break keyword
In the switch statement, we can also use the break statement keyword to come out of the switch block immediately with no further comparisons. This immediately transfers control to the statement following the loop. This is useful when you need to exit the switch comparison.
The following program demonstrates break keywords in Java.
Program
class Main {
public static void main(String args[]) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break; // Exits the switch statement
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
// Output: Wednesday
}
}
Output
Wednesday
The default keyword
Java’s ‘default’ keyword in a ‘switch’ statement specifies a block of source code that is to be executed if none of the ‘case’ values match the expression ‘switch’. Much like an ‘else’ block of an ‘if-else’ statement, it works as a default or fallback action.
The following program demonstrates the default keyword in the switch.
Program
public class SwitchExample {
public static void main(String[] args) {
int day = 5;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println(dayName); // Output: Friday
}
}
Output
Friday
Difference between switch and if-else statement
Here’s a comparison of Java’s ‘switch’ and ‘if-else’ statements.
Aspect
Switch Statement
If-else Statement
Syntax
switch(exp){
case 1; //statement
break ;
case 2: // statement
break;
default: //statement.
}
if(condition){
// statement }else{
// statement
}
Number of Conditions
Ideal for a large number of discrete values
It is more suitable for a smaller number of conditions or complex conditions.
Default Case
It supports a default case to handle any values not covered by the ‘case’ statement.
The no direct equivalent. You need to handle default conditions separately using ‘else’.
Complex Conditions
They are limited to simple value matches and cannot handle complex conditions or ranges.
This can handle complex boolean expressions and ranges.
Nested Switch Statement in Java
When a developer switch statement is placed inside another, it is called a nesting switch statement. This allows for more complex decision-making processes, where the outcome of one ‘switch’ statement can determine which nested ‘switch’ statement should be evaluated.
The following program demonstrates the nesting switch statement in Java language:
Program
public class NestedSwitchExample {
public static void main(String[] args) {
String branch = "CSE";
int year = 2;
switch (branch) {
case "CSE":
switch (year) {
case 1:
System.out.println("Subjects: Mathematics, Physics, Chemistry");
break;
case 2:
System.out.println("Subjects: Data Structures, Computer Networks, Operating Systems");
break;
case 3:
System.out.println("Subjects: Database Management Systems, Software Engineering");
break;
case 4:
System.out.println("Subjects: Artificial Intelligence, Machine Learning");
break;
default:
System.out.println("Invalid year");
break;
}
break;
case "ECE":
switch (year) {
case 1:
System.out.println("Subjects: Mathematics, Physics, Chemistry");
break;
case 2:
System.out.println("Subjects: Circuit Theory, Signals and Systems, Analog Electronics");
break;
case 3:
System.out.println("Subjects: Digital Electronics, Communication Systems");
break;
case 4:
System.out.println("Subjects: VLSI Design, Embedded Systems");
break;
default:
System.out.println("Invalid year");
break;
}
break;
default:
System.out.println("Invalid branch");
break;
}
}
}
Output
Subjects: Data Structures, Computer Networks, Operating Systems
In Java, the ‘switch’ statement provides a structured and efficient way to address several discrete values of an expression. The ‘switch’ statement evaluates an expression and passes control flow to the matching ‘case’ label, wherein the execution of the associated source code block is carried out.
Thus, the switch statement proves very helpful when dealing with a predefined set of values. Proper understanding and utilization of the ‘switch’ statement can significantly improve your source code’s readability and maintainability. The ‘switch’ statement, therefore, proves to be a very useful tool for developers in case they have to deal with multiple conditional branches based on a single expression.
FAQs
What is ‘switch’ statement in Java?
A ‘switch’ statement in Java is a control flow statement that allows you to execute different blocks of statements depending on the value of the expression. It is typically used to simplify multiple conditional branches that compare a single variable against different values.
What data types are supported in a ‘switch’ statement?
The ‘switch’ statement supports the following data types.
byte
short
int
char
string
enum
What is the purpose of the ‘default’ case in a ‘switch’ statement?
The ‘default’ case is optional and is a fallback when none of the ‘case’ labels match the expression. It provides a way to handle unexpected values and ensures that the ‘switch’ statement can handle all possible inputs.
Can ‘case’ labels include methods or function calls?
No, ‘case’ labels cannot include methods or function calls. The value in each ‘case’ label must be a compile-time constant, such as a literal or an enum constant.
Can you return a value from a ‘switch’ statement?
Yes, we can return a value from within a 'switch' statement. For this, we need to add the statement 'return' inside one of the blocks of 'case' or 'default.' It's a very common practice in methods that return different values depending on their input.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.