Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
Now Reading
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Welcome to an exciting journey into the heart of Java programming - the switch case in Java. We know that complex ‘if-else’ chains can become daunting. Hence, we introduce you to the power and simplicity of the switch case mechanism. It is a tool that enhances readability and elegantly simplifies your coding tasks. This comprehensive tutorial is designed to ignite your enthusiasm and elevate your programming skills.
The general syntax for a switch case in Java is as follows:
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// ...
default:
// Code to be executed if expression doesn't match any case values
}
Here, the ‘expression’ is evaluated once and compared with the values of each ‘case.’ If a match is found, the corresponding code block is executed. The ‘default’ code block is executed if there's no match.
Here's an example with switch case Java 17.
String day = "Sunday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println("It's a weekday");
break;
case "Saturday":
case "Sunday":
System.out.println("It's a weekend");
break;
default:
System.out.println("Invalid day");
}
Here, the switch expression is the ‘day’ string. The program compares ‘day’ with each case. If it is any of the weekdays, the program prints, "It's a weekday." If ‘day’ is "Saturday" or "Sunday," the program prints "It's a weekend." If ‘day’ doesn't match any case, the program prints "Invalid day."
The 'break' statement is used to terminate the execution of the currently running case in the switch block. If omitted, the switch case will continue (fall through) to the next case. The 'default' keyword denotes a block of code to be executed if no cases match the switch expression. It's not mandatory but recommended to handle unexpected cases.
When discussing the Switch Case in Java, it's vital to underscore the significance of the ‘Break’ and ‘Default’ statements. The ‘Break’ plays a key role in the operation of a switch case mechanism. It terminates the switch statement and transfers the execution to the next sequence of code. Without a ‘Break’ statement, the program would continue executing the next case, leading to incorrect results and inefficiency, known as a fall-through.
The ‘Default’ statement is another vital component. It is executed when none of the cases match the switch expression, serving as a catch-all clause. This ensures that our switch case statement produces output even in scenarios where the switch expression doesn't match any predefined case.
When dealing with a switch case in Java string, the importance of ‘Break’ and ‘Default’ statements cannot be overstated.
A flow diagram can be a valuable tool to grasp Java's switch case concept fully. It visually breaks down the sequence of operations in a switch case statement, making it easier to understand the process.
First, picture a ‘start point,’ from which an arrow leads to a box. This box represents the switch expression evaluation – the heart of our switch case in Java 8. It determines which path our program takes next.
Follow this graphical representation for a better understanding:
The switch expression must be of byte, short, int, char, enum type, or String. It doesn't work with long, float, double, or boolean.
int month = 2;
switch (month) {
// case statements
}
Each case value must be a unique literal or constant expression. Duplicate are not allowed.
char grade = 'B';
switch(grade) {
case 'A':
// code block
break;
case 'B':
// code block
break;
default:
// code block
}
In this Java code, the ‘switch’ statement evaluates ‘grade’ as 'B,' executing the corresponding ‘case 'B': code block then exits due to the ‘break’ statement.
Although not mandatory, it's a good practice to include a break statement in each case to prevent fall-through, where control would continue on to the next case's code.
String day = "Monday";
switch(day) {
case "Monday":
// code block
break; // prevents fall-through
default:
// code block
}
The default case, while not required, is recommended. It catches any cases not specifically handled and prevents undefined behavior.
int num = 5;
switch(num) {
case 1:
// code block
break;
case 2:
// code block
break;
default:
// code block for all other values of num
}
The order of cases doesn't matter unless you intentionally want to use fall-through.
int number = 2;
switch(number) {
case 3:
// code block
break;
case 2: // This will be executed regardless of its position
// code block
break;
default:
// code block
}
These rules ensure that your switch statement works correctly and efficiently. If you adhere to these, the switch case statement in Java can be a powerful tool for controlling program flow.
Before Java SE 7, switch statements could only handle primitive integer types (byte, short, char, int) and enums, but with its arrival, the ability to use String objects in switch statements was introduced. See it in the below example.
public class Main {
public static void main(String[] args) {
String dayOfWeek = "Tuesday";
switch (dayOfWeek) {
case "Monday":
System.out.println("Start of the work week");
break;
case "Tuesday":
System.out.println("Time for meetings");
break;
case "Wednesday":
System.out.println("Midweek work");
break;
case "Thursday":
System.out.println("Almost there");
break;
case "Friday":
System.out.println("End of the work week");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend!");
break;
default:
System.out.println("Invalid day");
}
}
}
Here, the switch statement checks the ‘dayOfWeek’ string and matches it with the case values. Each case checks if the‘dayOfWeek’ string equals a specific day string. When it finds a match, it executes the code in that case block. In this instance, since ‘dayOfWeek’ is "Tuesday", the console will print "Time for meetings".
Time for meetings
[Execution complete with exit code 0]
Switch statement comparisons are case-sensitive. The string "Monday" is not the same as "monday". Also, null values in the switch expression will throw a NullPointerException.
At its core, a switch statement is a multi-way branch statement. It provides an easier method of dispatching the execution to different parts of code based on the value of the expression.
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
}
}
In this example, the switch expression is ‘day.’ The switch statement evaluates this and tries to find a match among the available case values. If an equivalent is found, it executes the code associated with that case. It executes the code within the ‘default’ case if no match is found.
In our example, ‘day’ is 3, which corresponds to "Tuesday." Therefore, "Tuesday" is printed on the console.
Tuesday
[Execution complete with exit code 0]
When discussing Java switch multiple cases, you must note that a single block of code can be executed for multiple case values. This is done by stacking the case statements without a break statement between them.
public class Main {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1:
case 2:
System.out.println("Number is either 1 or 2");
break;
default:
System.out.println("Number is not 1 or 2");
}
}
}
In this example, if ‘number’ is either 1 or 2, the program will print "Number is either 1 or 2". Here, the switch case handles multiple cases (1 and 2) with the same block of code, showing how you can use Java switch multiple cases to simplify your code.
Number is either 1 or 2
[Execution complete with exit code 0]
Nested switch case statements occur when a switch statement is placed inside another switch statement. This nesting can be as deep as you want it to be.
public class Main {
public static void main(String[] args) {
int outer = 1;
int inner = 2;
switch(outer) {
case 1:
System.out.println("Outer switch: case 1");
switch(inner) {
case 1:
System.out.println("Inner switch: case 1");
break;
case 2:
System.out.println("Inner switch: case 2");
break;
default:
System.out.println("Inner switch: No matching case found");
}
break;
case 2:
System.out.println("Outer switch: case 2");
break;
default:
System.out.println("Outer switch: No matching case found");
}
}
}
In this example, there is an outer switch statement with two cases and an inner switch statement with two cases nested within the first case of the outer switch.
When ‘outer’ is 1, the first case of the outer switch statement is executed. Inside this case, the ‘inner’ switch statement is encountered, which tests ‘inner’. Since ‘inner’ is 2, the second case of the inner switch statement is executed, printing "Inner switch: case 2".
Outer switch: case 1
Outer switch: case 2
[Execution complete with exit code 0]
Although the switch statement in Java traditionally works with primitive data types (byte, short, char, int), their wrappers, and enumerated types and Strings, it's worth noting that wrapper classes can also be utilized in switch statements.
Wrapper classes provide a way to use primitive data types (int, char, etc.) as objects. The Java library includes an object wrapper class for each of the eight primitive data types.
Here's a simple example demonstrating the use of an Integer wrapper class in a switch statement:
public class Main {
public static void main(String[] args) {
Integer number = Integer.valueOf(3);
switch (number) {
case 1:
System.out.println("You entered one");
break;
case 2:
System.out.println("You entered two");
break;
case 3:
System.out.println("You entered three");
break;
default:
System.out.println("Invalid number entered");
}
}
}
This program creates an ‘Integer’ object, ‘number,’ and assigns it a value of 3. The switch statement evaluates this ‘Integer’ object. Since Java automatically unboxes the ‘Integer’ to an ‘int’ for the switch case evaluation, the case corresponding to 3 is matched, and "You entered three" is printed to the console.
You entered three
[Execution complete with exit code 0]
The ‘Scanner’ class in Java is a widely used tool for taking user input. When combined with a switch case statement, it offers a dynamic way to control the flow of your program based on user input. Here's a simple example to illustrate this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 1 and 3:");
int number = scanner.nextInt();
switch (number) {
case 1:
System.out.println("You entered one");
break;
case 2:
System.out.println("You entered two");
break;
case 3:
System.out.println("You entered three");
break;
default:
System.out.println("Invalid number entered");
}
scanner.close();
}
}
This Java program accepts an integer input from the user. If you pass 1, 2, or 3 to the main function through the console input, the program will print "You entered one," "You entered two," or "You entered three," respectively.
For example, if you run the program and input '1' when prompted, the output will be:
Enter a number between 1 and 3:
1
You entered one
If you input any number other than 1, 2, or 3, it will print "Invalid number entered." For instance, inputting '5' would result in the following:
Enter a number between 1 and 3
5
Invalid number entered
In the context of the switch case in Java using Scanner, we design a program that accepts user input to control its flow. We import the Scanner class and create a Scanner object to capture user input. The user is prompted to input a number between 1 and 3, which is read by the ‘nextInt()’ method and stored in a variable. This variable is then evaluated by a switch case statement, which prints a specific output based on the entered number. In the end, we close the Scanner object to avoid resource leaks.
An example of switch cases in Java programs with user input is detailed here.
Let's consider a simple program where the user inputs a number corresponding to a day of the week, and the program outputs the name of the day:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 1 and 7 representing a day of the week:");
int day = scanner.nextInt();
switch (day) {
case 1:
System.out.println("You entered: Sunday");
break;
case 2:
System.out.println("You entered: Monday");
break;
case 3:
System.out.println("You entered: Tuesday");
break;
// ... Continue for the rest of the week
default:
System.out.println("Invalid number entered");
}
scanner.close();
}
}
Here, a Scanner object captures user input, which is then evaluated by a switch case statement to determine the day of the week. The day's name is printed based on the user's input. If an invalid number is entered, a default message is displayed.
To bolster your understanding of switch case statements, it's valuable to tackle some practice questions. Here are a few to get you started:
Write a Java program that asks the user to enter a number from 1 to 7, each representing a day of the week. 1 represents Sunday, 2 represents Monday, and so on. The program should then print out the name of the day. Use a switch case statement for this task.
Create a program where the user inputs a letter grade (A, B, C, D, or F). The program should then output the corresponding qualitative description (e.g., 'A' for 'Excellent,' 'B' for 'Good,' etc.). Use a switch case statement to match the grade letters with their descriptions.
Write a Java program that performs basic arithmetic operations. It should take two numbers and an operator (+, -, *, /) as input from the user and perform the appropriate calculation using a switch case statement.
The switch case statement in Java is a powerful control flow structure that increases readability and efficiency in certain situations. The switch case shows versatility with user input via the Scanner class or application in nested scenarios. Whether you're dealing with primitive types, wrapper classes, or strings, mastering this construct is a beneficial addition to your Java programming skill.
Null can’t be used in a switch case. If you try to use null, Java will show a NullPointerException.
If you omit the break statement in a switch case, the "fall-through" behavior occurs. This means that if a case matches, the program will execute the matched one and all the cases after it encounters a break statement or reaches the end of the switch block. This can be leveraged intentionally in some situations, but generally, it's advisable to use break statements to avoid unintended outcomes.
The limitations of a switch statement are:
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...