In Java, the switch statement is utilized to execute a single statement based on various conditions. It functions similarly to an if-else-if ladder statement. The switch statement is compatible with byte, short, int, long, enum types, String, as well as certain wrapper types like Byte, Short, Integer, and Long. Starting from Java 7, it is possible to incorporate strings within the switch statement.
What Is switch Statement in Java?
The switch statement is utilized as a control flow construct in programming to direct the flow of program execution and trigger different branches of code depending on the value of an expression.
In simpler terms, the switch statement checks if a variable is equal to various values.
Rules and Constraints of Java Switch Statement
There are several rules and constraints of Java switch statement. Some of them are as follows:
- There can be one or N case values for a switch expression.
- The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables .
- The case values must be unique. In case of a duplicate value, it renders a compile-time error.
- The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
- Each case statement can have a break statement, which is optional. When control reaches the break statement , it jumps to the control after the switch expression. If a break statement is not found, the next case is executed.
- The case value can have a default label, which is optional.
In Java, the switch statement offers a more detailed option that eliminates the need for nested or multiple if-else statements when dealing with a single variable.
In the Java switch statement syntax, the switch keyword precedes an expression enclosed in parentheses that will be evaluated. This expression is required to result in a specific data type, typically a primitive type like int, char, or enum.
Syntax of Switch Statement
Here is the syntax of switch statement:
switch(expression) {
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
Code to be executed if all cases are not matched.
}
Flowchart of Switch Statement
The images below illustrate the operational flow of a switch statement:
In Java, the switch statement allows for the inclusion of a default label, which is designed to run when none of the case labels correspond to the value of the expression. While not mandatory, incorporating a default label can be beneficial when dealing with unforeseen inputs or values.
Next, we will explore various instances to illustrate how the Switch Statement operates in different scenarios.
Different Examples of switch Statement
To comprehend the switch statement concept in Java, work through the exercises provided below:
Example 1: Simple Switch Statement
To illustrate how the switch statement functions in Java, we will work through an example.
Example
public class Main {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
Example 2: Finding Month using switch Statement
Consider this example to illustrate how you can identify months by utilizing the switch statement in Java.
Example
//Java Program to demonstrate the example of the Switch statement, where we are printing the month name for the given number
public class Main {
public static void main(String[] args) {
//Specifying month number
int month=7;
String monthString="";
//Switch statement
switch(month){
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
//Printing the month of the given number
System.out.println(monthString);
}
}
Output:
7 - July
Example 3: Checking Vowel or Consonant
In the context of characters, if a letter is either A, E, I, O, or U, it is classified as a vowel; otherwise, it is categorized as a consonant. The classification is not influenced by the letter's case.
Example
public class Main {
public static void main(String[] args) {
char ch='O';
switch(ch) {
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
case 'A':
System.out.println("Vowel");
break;
case 'E':
System.out.println("Vowel");
break;
case 'I':
System.out.println("Vowel");
break;
case 'O':
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
Output:
Java Switch Statement is a fall-through
In Java, the switch statement exhibits fall-through behavior, where it will continue to execute all subsequent statements after the first match if a break statement is omitted.
Example
//Java Switch Example where we are omitting the break statement
public class Main {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
30
Not in 10, 20 or 30
Java Switch Statement with String
Starting from Java 7, Java introduced the capability to utilize strings within switch expressions, with the condition that the case statement needs to be a string literal.
Example
//Java Program to demonstrate the use of Java Switch statement with String
public class Main {
public static void main(String[] args) {
//Declaring String variable
String levelString="Expert";
int level=0;
//Using String in Switch expression
switch(levelString){
//Using String Literals in Switch Case
case "Beginner": level=1;
break;
case "Intermediate": level=2;
break;
case "Expert": level=3;
break;
default: level=0;
break;
}
System.out.println("Your Level is: "+level);
}
}
Output:
Your Level is: 3
Java Nested Switch Statement
A nested switch statement in Java involves utilizing a switch statement within another switch statement. This programming technique allows for a more intricate control flow structure in Java programs.
Example
//Java Program to demonstrate the use of Java Nested Switch
public class Main {
public static void main(String args[]) {
//C - CSE, E - ECE, M - Mechanical
char branch = 'C';
int collegeYear = 4;
switch( collegeYear ) {
case 1:
System.out.println("English, Maths, Science");
break;
case 2:
switch( branch ) {
case 'C':
System.out.println("Operating System, Java, Data Structure");
break;
case 'E':
System.out.println("Micro processors, Logic switching theory");
break;
case 'M':
System.out.println("Drawing, Manufacturing Machines");
break;
}
break;
case 3:
switch( branch ) {
case 'C':
System.out.println("Computer Organization, MultiMedia");
break;
case 'E':
System.out.println("Fundamentals of Logic Design, Microelectronics");
break;
case 'M':
System.out.println("Internal Combustion Engines, Mechanical Vibration");
break;
}
break;
case 4:
switch( branch ) {
case 'C':
System.out.println("Data Communication and Networks, MultiMedia");
break;
case 'E':
System.out.println("Embedded System, Image Processing");
break;
case 'M':
System.out.println("Production Technology, Thermal Engineering");
break;
}
break;
}
}
}
Output:
Data Communication and Networks, MultiMedia
Using enum in Switch Statement
In Java, we can employ an enumeration in a switch statement. An enumeration in Java is a type that defines a set of constants (unchangeable, similar to constant variables). To create an enumeration, we utilize the keyword "enum" and list the constants inside curly brackets, which are delimited by commas.
Example
//Java Program to demonstrate the use of Enum in switch statement
public class Main {
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
public static void main(String args[]) {
Day[] DayNow = Day.values();
for (Day Now: DayNow) {
switch (Now) {
case Sun:
System.out.println("Sunday");
break;
case Mon:
System.out.println("Monday");
break;
case Tue:
System.out.println("Tuesday");
break;
case Wed:
System.out.println("Wednesday");
break;
case Thu:
System.out.println("Thursday");
break;
case Fri:
System.out.println("Friday");
break;
case Sat:
System.out.println("Saturday");
break;
}
}
}
}
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Java Wrapper in Switch Statement
In Java, it is possible to utilize four wrapper classes - Byte, Short, Integer, and Long - within a switch statement.
Example
//Java Program to demonstrate the use of the Wrapper class in a switch statement
public class Main {
public static void main(String args[]) {
Integer age = 18;
switch (age) {
case (16):
System.out.println("You are under 18.");
break;
case (18):
System.out.println("You are eligible to vote.");
break;
case (65):
System.out.println("You are senior citizen.");
break;
default:
System.out.println("Please give the valid age.");
break;
}
}
}
Output:
You are eligible to vote.
Features and Limitations of Java Switch Statement
There are several features and limitations of the Java Switch Statament. Some of them are as follows:
- One of the major important features of the Java Switch statement is its fall-through behaviour. It means that if a case label does not contain a break statement, execution will be passed directly to the next case label. A switch statement can also include a default label, which is executed if none of the case labels match the expression's value. The default label is optional but can be useful for handling unexpected or unspecified values.
- Switch statements can only match exact values, and they cannot check ranges of values. This means that if you need to check for a range of values, you would need to use multiple case labels or resort to other control flow statements, such as if-else.
- Switch statements can only be used to check for equality between the expression and the case labels. They cannot perform more complex checks, such as checking conditions or using comparison operators.
- The expression in a switch statement must evaluate to a primitive data type (int, char, or enum) or a String (since Java 7). This limitation restricts the types of expressions that can be used with switch statements, making them less flexible in certain situations compared to other control flow statements.
- It's worth noting that starting from Java 12, switch statements have been enhanced to support switch expressions, which allow the switch statement to be used as an expression that returns a value. This feature offers more flexibility and can result in more concise and readable code in certain situations.
- Overall, the switch statement in Java is a powerful tool for controlling the flow of a program based on the value of an expression, offering a clear and efficient way to handle multiple branching scenarios.
- Switch statements can sometimes lead to code duplication, especially when multiple case blocks perform similar actions. It can make the code harder to maintain and debug.
- While switch statements can be used with String objects since Java 7, they cannot be used directly with other object types. This limitation can make switch statements less useful in scenarios where complex objects need to be compared and evaluated.