As we discussed in our previous article, decision-making is a fundamental aspect of any application. Besides the if-else structure, the switch-case is also a powerful tool to make decisions and to handle multiple conditions. This article aims to help beginners to understand the concept of Java switch-case in depth. We will try to explore the syntax, functionality, and best practices with real-world examples.
The switch case statement in Java allows the program to
select one execution path among many based on the value of an expression. It
provides a structured and efficient way to handle multiple conditions. Sometimes,
it is beneficial to use Java switch-case structure instead of Java if-else-if structure
when it comes to efficiency.
Syntax:
The syntax of the switch case statement consists of the switch
keyword followed by an expression enclosed in parentheses. This expression is
then compared to various cases in the body of the switch case. If none of the case
conditions is matched, a default case is used to handle this situation in the Java switch case. The default case is usually used at the end of all cases but it is
not necessary to use it at the end. It can be used anywhere case hierarchy.
The break statement is present at the end of every
case. If the break is not used, the execution would continue on into the code
segment of the next case without even checking the case value. Let's suppose, a
switch statement has five cases and the value of the third case matches the
value of the expression. If no break statement were present at the end of the third
case, all the cases after case 3 would also get executed along with case 3
resulting in more time consumption. It is to note that there is no break after the default case.
Following flow diagram can also help to understand the concept.
Syntax
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;
}
The switch expression defines the value that will be
evaluated against the cases. It can be of various data types, including
primitive types, enumerations, and strings.
Let's take a look at an example:
int dayOfWeek = 3;
String dayName;
switch (dayOfWeek) {
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;
default:
dayName =
"Invalid day";
break;
}
System.out.println("Today is " + dayName);
In this example, the value of the variable `dayOfWeek` is
evaluated against different cases. The corresponding `dayName` is assigned
based on the matching case. If none of the cases match, the default case is
executed.
Case Statements:
Case statements define the different conditions to be
evaluated against the switch expression. We can compare values using literals,
variables, and constant expressions. Here's an example that demonstrates the
usage of variables in case statements:
int month = 3;
String season;
switch (month) {
case 12:
case 1:
case 2:
season =
"Winter";
break;
case 3:
case 4:
case 5:
season =
"Spring";
break;
case 6:
case 7:
case 8:
season =
"Summer";
break;
case 9:
case 10:
case 11:
season =
"Autumn";
break;
default:
season =
"Invalid month";
break;
}
System.out.println("The current season is " +
season);
In this example, we use multiple cases for each season,
taking advantage of the fall-through behavior. If the value of `month` matches
any of the specified cases, the corresponding season is assigned.
The Default Case:
The default case is optional and serves as a fallback option
when none of the case conditions match the switch expression. It is executed if
no other case is a match. Here's an example:
int grade = 8.5;
String gradeLetter;
switch (grade) {
case 10:
case 9:
gradeLetter =
"A";
break;
case 8:
gradeLetter =
"B";
break;
case 7:
gradeLetter =
"C";
break;
case 6:
gradeLetter =
"D";
break;
default:
gradeLetter =
"F";
break;
}
System.out.println("Your grade is " +
gradeLetter);
In this example, the value of `grade` is 8.5, and the switch
expression evaluates the resulting grade category. The corresponding
`gradeLetter` is assigned based on the matching case. If none of the cases
match, the default case is executed, in our case ‘F’ is assigned to gradeLetter.
Practice Programs on Java switch-case structure:
Practice program 1:
Write a java switch-case program that takes three inputs from the user: an
operator and 2 numbers. It performs calculation based on numbers and operator
entered. Then the result is displayed on the screen.
Solution:
import java.util.Scanner;
public class Calculator {
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter the operator (+, -,
*, /): ");
char operator
= scanner.next().charAt(0);
System.out.print("Enter the first number: ");
double number1
= scanner.nextDouble();
System.out.print("Enter the second number: ");
double number2
= scanner.nextDouble();
double result;
switch (operator) {
case '+':
result
= number1 + number2;
System.out.println("Result: " + result);
break;
case '-':
result
= number1 - number2;
System.out.println("Result: " + result);
break;
case '*':
result
= number1 * number2;
System.out.println("Result: " + result);
break;
case '/':
if
(number2 != 0) {
result = number1 / number2;
System.out.println("Result: " + result);
} else
{
System.out.println("Error: Division by zero is not allowed.");
}
break;
default:
System.out.println("Invalid operator entered.");
}
}
}
Output:
Enter the operator (+, -, *, /): *
Enter the first number: 1.4
Enter the second number: -5.3
Result: -7.419999999999999
Explanation:
In this program, the user is prompted to enter an operator
(+, -, *, /), followed by two numbers. The program then uses a switch-case
statement to perform the corresponding calculation based on the operator
entered. The result is displayed on the screen.
Please note that error handling is included for the division
operation to prevent division by zero, and an error message is displayed in
such cases.
Practice program 2:
Write a Java program that prompts the user to enter a grade.
Your program should display the corresponding meaning of grade as per the
following table
Grade |
Meaning |
A |
Excellent |
B |
Good |
C |
Average |
D |
Deficient |
F |
Failing |
Solution:
import java.util.Scanner;
public class GradeMeaning{
public static void
main(String[] args) {
char grade; //
To hold grade
// Create a
Scanner object to read input.
Scanner
console = new Scanner(System.in);
// Get grade
from the user.
System.out.print("Enter grade: ");
grade =
console.next().charAt(0);
// Determine
and display grade
switch (grade)
{
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
case 'D':
System.out.println("Deficient");
break;
case 'F':
System.out.println("Failing");
break;
default:
System.out.println("Invalid input");
}
}
}
When you run the program, the output will be:
Enter grade: B
Good
Omitting the break statement:
As we have discussed earlier, break statement is optional.
If we omit the break, execution will continue on into the next case. It is
sometimes desirable to have multiple cases without break statements between
them.
Let us understand this with the help of an example:
public class SwitchWithoutBreak {
public static void main(String[] args) {
int number=20;
switch(number){
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");
}
}
}
When you run the program, the output will be:
20
30
Not in 10, 20 or 30
If-else-if vs Java switch-case:
The if-else if statement allows you to specify multiple
conditions and execute different blocks of code based on the outcome of each
condition. It provides a more flexible and expressive way to handle complex
conditional logic.
On the other hand, the switch-case statement is used when
you have a single variable or expression that you want to compare against
multiple values. It provides a more concise way to handle multiple conditions.
In this guide, we've explored the ins and outs of the Java
switch case statement. By understanding its syntax, working principles, and
best practices, you are now equipped to leverage this powerful construct in
your Java programming endeavors.