For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Are you tired of writing complex if-else chains in your Java code? Switch case in Java Programming offers a cleaner, more readable alternative for handling multiple conditions. This guide explores what is switch case in Java, how to use switch case in Java effectively, and provides practical switch case program in Java examples that you can implement in your projects right away.Switch case statement in Java is a powerful control structure that enhances code readability while simplifying your programming tasks.
Build a strong foundation in Java and beyond. Join the Software Engineering course by upGrad to accelerate your tech journey.
A switch case statement in Java is a control flow mechanism that allows a program to evaluate an expression against multiple values and execute different code blocks based on matching cases. It provides a more elegant alternative to lengthy if-else-if chains, especially when comparing a single variable against several possible values.
Take your Java skills to the next level with a Professional Certificate in Cloud Computing and DevOps.
The switch case in Java follows a specific structure that evaluates an expression once and compares it with multiple case values to determine which code block to execute.
switch (expression) {
case value1:
// Code to execute when expression equals value1
break;
case value2:
// Code to execute when expression equals value2
break;
// More cases as needed
default:
// Code to execute when no cases match
}
In this structure, the expression is evaluated once, and its value is compared with each case. When a match is found, the corresponding code block executes. If no matches are found, the default block runs.
Tech-savvy leaders with Java expertise are shaping the AI future. Join the Executive Programme in Generative AI by IIIT-B to explore strategic applications of AI.
To effectively implement switch case in Java, follow these important rules:
Let's explore how to write switch case in Java with practical examples.
Problem Statement: Create a program that converts a numerical day (1-7) into the corresponding day of the week name.
public class DayCalculator {
public static void main(String[] args) {
int day = 3; // Represents Wednesday
// Converting day number to day name using switch case
switch (day) {
case 1:
System.out.println("It's Sunday");
break;
case 2:
System.out.println("It's Monday");
break;
case 3:
System.out.println("It's Wednesday");
break;
case 4:
System.out.println("It's Thursday");
break;
case 5:
System.out.println("It's Friday");
break;
case 6:
System.out.println("It's Saturday");
break;
case 7:
System.out.println("It's Sunday");
break;
default:
System.out.println("Invalid day number");
}
}
}
Output:
It's Wednesday
This example demonstrates how switch case simplifies converting numeric values to corresponding text descriptions, a common task in many applications.
Problem Statement: Implement a basic calculator that performs addition, subtraction, multiplication, or division based on user input.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number:");
double num1 = scanner.nextDouble();
System.out.println("Enter second number:");
double num2 = scanner.nextDouble();
System.out.println("Enter operation (+, -, *, /):");
char operation = scanner.next().charAt(0);
double result;
// Using switch case to perform different operations
switch (operation) {
case '+':
result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break;
case '/':
// Check for division by zero
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Cannot divide by zero");
}
break;
default:
System.out.println("Error: Invalid operation");
}
scanner.close();
}
}
Output (for inputs 10, 5, and '+'):
Enter first number:
10
Enter second number:
5
Enter operation (+, -, *, /):
+
Result: 15.0
This calculator example shows how switch case can handle different operations based on user input, a practical application in many utility programs.
Problem Statement: Create a program that provides different messages based on a user's subscription level.
public class SubscriptionManager {
public static void main(String[] args) {
String plan = "Premium"; // User's subscription plan
// Providing features based on subscription level
switch (plan) {
case "Basic":
System.out.println("You have access to basic features");
break;
case "Standard":
System.out.println("You have access to standard features");
System.out.println("Including: HD streaming and multi-device support");
break;
case "Premium":
System.out.println("You have access to all premium features");
System.out.println("Including: Ultra HD, multi-device, and offline downloads");
break;
default:
System.out.println("Unknown subscription plan");
}
}
}
Output:
You have access to all premium features
Including: Ultra HD, multi-device, and offline downloads
This example demonstrates how to use switch case with String values, perfect for menu systems or configuration settings in real applications.
Problem Statement: Create a program that identifies whether a day is a weekday or weekend.
public class WeekdayChecker {
public static void main(String[] args) {
String day = "Saturday"; // The current day
// Checking if day is weekday or weekend
switch (day) {
// Grouping weekdays together
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println(day + " is a weekday");
break;
// Grouping weekend days
case "Saturday":
case "Sunday":
System.out.println(day + " is a weekend");
break;
default:
System.out.println("Invalid day name");
}
}
}
Output:
Saturday is a weekend
This example shows how to efficiently handle multiple cases with the same output, eliminating redundant code.
Here's a practical example showing how to use the Scanner class with switch case in Java to create interactive programs:
Problem Statement: Create a menu-driven program that allows users to convert temperatures between Celsius and Fahrenheit.
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Temperature Converter");
System.out.println("1. Celsius to Fahrenheit");
System.out.println("2. Fahrenheit to Celsius");
System.out.print("Enter your choice (1 or 2): ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();
double fahrenheit = (celsius * 9/5) + 32;
System.out.printf("%.1f°C = %.1f°F", celsius, fahrenheit);
break;
case 2:
System.out.print("Enter temperature in Fahrenheit: ");
double fahr = scanner.nextDouble();
double cels = (fahr - 32) * 5/9;
System.out.printf("%.1f°F = %.1f°C", fahr, cels);
break;
default:
System.out.println("Invalid choice! Please select 1 or 2.");
}
scanner.close();
}
}
Output (for choice 1 and temperature 25°C):
Temperature Converter
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your choice (1 or 2): 1
Enter temperature in Celsius: 25
25.0°C = 77.0°F
This temperature converter demonstrates how switch case can create user-friendly menu systems in real-world applications.
Switch case in Java works best when:
If-else is better when:
Switch case in Java is a powerful tool that makes your code cleaner and easier to read. Instead of writing long chains of if-else statements, you can use switch case to handle multiple options in a more organized way.
Think of switch case as a menu selector, you give it a value, and it jumps directly to the matching option. This makes your programs faster and simpler, especially when working with menu systems, user input choices, or any situation where you need to compare one value against several possibilities.
Whether you're creating a simple calculator, processing user selections, or handling different states in your application, switch case in Java helps you write better code with fewer errors. Master this feature, and you'll save time while creating more professional Java applications.
Without break statements, switch case will "fall through" and execute all code blocks after the matching case until it reaches a break or the end of the switch. This behavior can be intentionally used for multiple cases that should execute the same code, but often leads to unexpected results when unintentional.
No, switch case in Java only supports byte, short, int, char, String, and enum types. Float and double are not supported because floating-point equality comparisons can be problematic due to precision issues, making them unsuitable for switch expressions.
Switch case performs case-sensitive equality checks on strings. "Hello" and "hello" are treated as different cases. Behind the scenes, Java uses the String.equals() method to compare the values, ensuring proper string comparison rather than reference comparison.
No, case values must be compile-time constants. Variables or expressions that aren't constant can't be used. This restriction exists because the compiler needs to build efficient jump tables for switch statements, which requires knowing all possible values at compile time.
For multiple conditions, switch case can be more efficient as the compiler can optimize it into a jump table, whereas if-else chains require sequential evaluation. With a large number of cases, this optimization can result in O(1) constant-time performance instead of O(n) linear-time checks.
String support in switch statements was added in Java 7 (released in 2011). This feature significantly enhanced switch case functionality, allowing for more readable and maintainable code when working with string-based comparisons, which are common in many applications.
No, case values must be constant expressions that can be evaluated at compile time. You cannot use variables or method calls directly in case statements. This is because the Java compiler needs to know all possible case values during compilation to optimize the switch statement.
Enum types work excellently with switch case because they provide type safety. Simply use the enum constant name (without qualification) in each case. This prevents errors from invalid values and makes your code more maintainable when you need to add or remove options in the future.
No, the default case is optional. However, including it is considered good practice as it handles unexpected inputs and makes your code more robust. Without a default case, if no matching case is found, the switch statement simply completes without executing any code.
Yes, you can have multiple case labels for the same code block by listing them sequentially without break statements between them. This technique is useful when you want different values to trigger the same action, reducing code duplication and improving maintainability.
While switch statements work with primitive types, they also work with their wrapper classes (Integer, Character, Byte, Short) through auto-unboxing. Java automatically converts between primitives and their wrapper objects, allowing you to use Integer objects in switch statements as if they were int primitives.
Java 12 introduced enhanced switch expressions that allow switch to return values and use arrow syntax (->). This modern approach eliminates break statements, prevents fall-through behavior, and enables more concise code with features like multiple case labels and expression-based results.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.