switch case in java
In the previous post, we have seen if..else if conditional statements. In this post, we will learn what is switch case in java.
switch case is an alternative of if else statements. It is used to control the flow of program. If we have multiple conditions to check, then instead of putting multiple elseif statements we can simplify it by using switch case statements. It improves readability of code.
The expression mentioned in switch keyword must return an int,String and enumerated value. There are multiple case blocks which will contains a set of statements to execute. On the basis on expression evaluation in the switch keyword, controls will be given to a particular case statement.
After executing statements under a particular case statement, break keyword will be put to exit that case statement.
Syntax of switch case:
switch ( expression or variable) { case value: set of statements; break; case value: set of statements; break; default: some other actions as value not caught above; }
Example of switch case:
public class ExampleSwitch { public static void main(String[] args) { String book = "python"; switch(book.toUpperCase()){ case "PHP" : System.out.println("It is a PHP book"); break; case "JAVA" : System.out.println("It is a JAVA book"); break; case "PYTHON" : System.out.println("It is a PYTHON book"); // Control is given to this case break; default: System.out.println("Book not found"); } } }
Another practical example:
We can see another example, where we are calling a method which is having switch case statements and returning day of the week.
public class ExampleSwitch { public static void main(String[] args) { String theDay = getDay(5); System.out.println("Today is "+theDay); } public static String getDay(int a){ String day; switch(a){ case 1 : day= "Monday"; break; case 2 : day= "Tuesday"; break; case 3 : day= "Wednesday"; break; case 4 : day= "Thursday"; case 5 : day= "Friday"; break; case 6 : day= "Saturday"; break; case 7 : day= "Sunday"; break; default: day= "No day found"; break; } return day; } }