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");	
		}
	}
}
Output: It is a PYTHON book

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;
	}

}
Output: Today is Friday
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *