Java Switch Case Statement

Java Switch Case Statement With Simple Program Examples: Today, we will learn another new topic in the Core Java tutorial series. That is Switch Case, and if you are not reading our previous post about If-Else In Java, you can check that by using that link. Switch case statements are used when several options are available, and we need to perform some specific tasks as per the selection.

Java includes a powerful and flexible control structure called the “switch case” statement among its many features. The switch case statement allows programmers to execute different blocks of code based on the value of a single variable or expression, making it a powerful tool for handling complex decision-making logic.

In this statement, a variable or expression is evaluated, and based on its value, control is transferred to the corresponding case block of code. This makes the switch case statement a useful alternative to long chains of if-else statements or nested if statements, which can be difficult to read and maintain.

In this Java tutorial blog post, we will explore the syntax and use cases of the switch case statement in Java and learn how to use it effectively in our code.

Java Switch Case Syntax

The switch case statement in Java is a branching construct that allows selecting one of several possible execution paths based on the value of a single variable or expression. The statement consists of the keyword “switch” followed by the variable or expression in parentheses and a series of “case” labels that represent possible values of the variable or expression. Each case label is followed by a block of code to be executed if the variable’s value matches the value specified in the case label. The switch case statement also provides a default label executed if none of the other case labels match the variable’s value.

The syntax of the switch case statement in Java is as follows:

switch(variable or expression) {
   case value1:
      // code to execute if variable or expression equals value1
      break;
   case value2:
      // code to execute if variable or expression equals value2
      break;
   .
   .
   .
   case valueN:
      // code to execute if variable or expression equals valueN
      break;
   default:
      // code to execute if variable or expression does not match any of the above cases
}

This syntax evaluates the variable or expression and compares it to each possible value specified in the case statements. If a match is found, the corresponding block of code is executed. The break statement exits the switch case block after the code for the matching case has been executed. The default case is used to specify code that will be executed if none of the other cases match.

It’s important to note that the variable or expression used in the switch case statement must be a primitive data type (such as int, char, or enum) or a string. The values specified in the case statements must also be the same data type.

One of the advantages of using the switch case statement is that it can result in more readable and efficient code. If we have a long list of if-else statements to handle a specific scenario, keeping track of the logic and making changes, if needed, can become difficult. A switch case statement can make the code more concise and easily understood.

Program: How do you use a Java switch case in a program?
package com.softwaretestingo.ConditionalStatements;
public class SwitchCase_Example 
{
	public static void main(String[] args) 
	{
		int dayOfWeek = 2;
		String dayString;

		switch (dayOfWeek) {
		case 1:
			dayString = "Monday";
			break;
		case 2:
			dayString = "Tuesday";
			break;
		case 3:
			dayString = "Wednesday";
			break;
		case 4:
			dayString = "Thursday";
			break;
		case 5:
			dayString = "Friday";
			break;
		case 6:
			dayString = "Saturday";
			break;
		case 7:
			dayString = "Sunday";
			break;
		default:
			dayString = "Invalid day";
			break;
		}
		System.out.println("Today is " + dayString);
	}
}

Output:

Today is Tuesday

In this example, we have an integer variable dayOfWeek That represents the current day of the week. We want to convert this integer value into a string representation of the day (e.g., “Monday,” “Tuesday,” etc.) so that we can print it out.

We start by declaring a string variable, dayString, that will hold the string representation of the day. We then use a switch case statement to evaluate the value of dayOfWeek and determine the corresponding string value to assign to dayString.

Each case statement in the switch block corresponds to one of the possible values of dayOfWeek. For example, if dayOfWeek is 2 (which represents Tuesday), the case statement case 2 will be executed, and the string value “Tuesday” will be assigned to dayString. The break statement exits the switch block after the code for the matching case has been executed.

The default case is used to specify what code should be executed if dayOfWeek does not match any of the case statements. If dayOfWeek is not between 1 and 7, we assign the string value “Invalid day” to dayString.

Finally, we print out the string representation of the current day by concatenating the string “Today is ” with the value of dayString.

This example demonstrates how the switch case statement can simplify decision-making logic in Java and produce more readable and efficient code.

Important Points Of Switch Statements

  • The case value cannot duplicate
  • The entered Value and the case Value must be the same data type.
  • The Value for the Case must be literal or constant. You can not use the variable in this case.
  • The Break statement is used inside the switch case to terminate the flow of the statement sequence.
  • The Break statement is optional. Without a break, the execution flow will continue to the next case.
  • The default statement in the switch case is optional and can appear anywhere in the switch block.
  • Java Switch case statements make the code readable by omitting if..else..if statements.
  • Ensure you use the Switch case string when you use Java 7; otherwise, you will get an exception.
  • You can use nested switch statements, which means you can use a switch case statement inside another switch case.

Conclusion:

The switch case statement is a powerful tool in the Java language that can be used to handle complex decision-making logic. By allowing us to execute different blocks of code based on the value of a single variable or expression, the switch case statement can make our code more readable and efficient. Understanding the syntax and proper use cases of the switch case statement is an important skill for any Java programmer.

If You find anything wrong and want to add more information, write in the comment section, and we will be happy to update you with your information.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment