What is a Switch Case in Java & How to Use It?
Updated on Nov 14, 2022 | 8 min read | 6.3k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 14, 2022 | 8 min read | 6.3k views
Share:
Table of Contents
The switch case in Java is one of the many Java statements that tell the programming language what to do. Like sentences in the English language that gives a complete idea of the text and include clauses, Java statements are commands including one or more expressions that the Java interpreter executes. In simpler terms, a Java statement is an instruction explaining what should happen.
A Java statement ends in a semicolon (;) and tells Java to process instructions up to that semicolon. By default, the Java interpreter follows the order in which statements are written and runs one statement after another. However, statements that control the program flow (flow-control statements), such as loops and conditionals, do not follow the default order of execution. This article focuses on one such type of selection control mechanism – the Java switch case statement.
Check out our free courses to get an edge over the competition
Java supports three kinds of statements: expression statements for changing values of variables, calling methods and creating objects, declaration statements for declaring variables, and control-flow statements for determining the order of execution of statements.
The Java switch case statement is a type of control-flow statement that allows the value of an expression or variable to change the control flow of program execution through a multi-way branch. In contrast to if-then and if-then-else statements, the Java switch statement has several execution paths. Switch case in Java works with short, byte, int, and char primitive data types. From JDK7, Java switch can also be used with String class, enumerated types, and Wrapper classes that wrap primitive data types such as Byte, Character, Integer, and Short.
Check out upGrad’s Advanced Certification in DevOps
The body of a switch case statement in Java is called a switch block. Every statement in the switch block is labelled using one or more cases or default labels. Hence, the switch statement evaluates its expression, followed by the execution of all the statements which follow the matching case label.
Given below is the syntax of the switch case statement:
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
// We can have any number of case statements
// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}
Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)
The following Java code example declares an int named “month” whose value represents one of the 12 months of the year. The code uses the switch case statement to display the month’s name based on the month’s value.
public class SwitchExample {
public static void main(String[] args) {
int month = 6;
String monthString;
switch (month) {
case 1: monthString = “January”;
break;
case 2: monthString = “February”;
break;
case 3: monthString = “March”;
break;
case 4: monthString = “April”;
break;
case 5: monthString = “May”;
break;
case 6: monthString = “June”;
break;
case 7: monthString = “July”;
break;
case 8: monthString = “August”;
break;
case 9: monthString = “September”;
break;
case 10: monthString = “October”;
break;
case 11: monthString = “November”;
break;
case 12: monthString = “December”;
break;
default: monthString = “Invalid month”;
break;
}
System.out.println(monthString);
}
}
Output: June
The break statement is an essential aspect of the Java switch case that terminates the enclosing switch statement. The break statement is required because without it, statements in the switch block would fall through. Thus, regardless of the expression of the succeeding case labels, all statements after the matching case label are sequentially executed until a break statement is encountered.
The following code is an example to show a switch block falling through in the absence of the break statement.
public class SwitchExampleFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 6;
switch (month) {
case 1: futureMonths.add(“January”);
case 2: futureMonths.add(“February”);
case 3: futureMonths.add(“March”);
case 4: futureMonths.add(“April”);
case 5: futureMonths.add(“May”);
case 6: futureMonths.add(“June”);
case 7: futureMonths.add(“July”);
case 8: futureMonths.add(“August”);
case 9: futureMonths.add(“September”);
case 10: futureMonths.add(“October”);
case 11: futureMonths.add(“November”);
case 12: futureMonths.add(“December”);
break;
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println(“Invalid month number”);
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
Output:
June
July
August
September
October
November
December
The above code displays the month of the year corresponding to the integer month and the months that follow. Here, the final break statement serves no purpose because the flow falls out of the switch statement. The use of the break statement is helpful because it makes the code less error-prone and modifications easier. The default section in the code handles all values not regulated by any of the case sections.
Switch statements in Java can have multiple case labels as well. The following code illustrates the same – here, the number of days in a particular month of the year is calculated.
class SwitchMultiple{
public static void main(String[] args) {
int month = 2;
int year = 2020;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println(“Invalid month.”);
break;
}
System.out.println(“Number of Days = “
+ numDays);
}
}
Output:
Number of Days = 29
Learn Online software development courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
A nested switch is when you use a switch as a part of the sequence of statements of an outer switch. In this case, there is no conflict between the case constants in the other switch and those in the inner switch because a switch statement defines its own block.
The following example demonstrates the use of nested Java switch-case statements:
public class TestNest {
public static void main(String[] args)
{
String Branch = “CSE”;
int year = 2;
switch (year) {
case 1:
System.out.println(“Elective courses : Algebra, Advance English”);
break;
case 2:
switch (Branch) // nested switch
{
case “CSE”:
case “CCE”:
System.out.println(“Elective courses : Big Data, Machine Learning”);
break;
case “ECE”:
System.out.println(“elective courses : Antenna Engineering”);
break;
default:
System.out.println(“Elective courses : Optimization”);
}
}
}
}
Output:
Elective courses: Big Data, Machine Learning
Beginning from JDK7, you can use a String object in the expression of a switch statement. The comparison of the string object in the switch statement’s expression with associated expressions of each case label is as if it was using the String.equals method. Also, the comparison of string objects in the switch statement expression is case-sensitive.
The following code example displays the type of game based on the value of the String named “game.”
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = “Cricket”;
switch(game){
case “Volleyball”: case”Football”: case”Cricket”:
System.out.println(“This is an outdoor game”);
break;
case”Card Games”: case”Chess”: case”Puzzles”: case”Indoor basketball”:
System.out.println(“This is an indoor game”);
break;
default:
System.out.println(“What game it is?”);
}
}
}
Output:
This is an outdoor game
It would be best if you keep certain rules in mind while using Java switch statements. Following is a list of the same:
Java has unmatched popularity among programmers and developers and is one of the most in-demand programming languages today. Needless to say, budding developers and software engineers who want to upskill themselves for the ever-evolving job market need to get a stronghold over their Java skills.
upGrad’s Job-linked PG Certification in Software Engineering is specially designed for freshers and final year candidates who want to learn to code and get placed into entry-level software roles.
If you are wondering what the 5-month online course entails, here are some highlights to give you an idea:
If you want to kickstart your journey towards a promising career in software engineering, here’s your chance to learn from the best.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources