Switch Statement in java 7

This tutorial describes the if statement in java 7. This is one kind of decision making statement.

Switch Statement in java 7

This tutorial describes the if statement in java 7. This is one kind of decision making statement.

Switch Statement in java 7

Switch Statement in java 7

This tutorial describes the if statement in java 7. This is one kind of decision making statement.

Switch Statements :

The switch statement is used when you want to test many statements based on some expression. This expression may be any int value, char value or enum value.
The switch block contains many cases according to requirement .It provides multiple selections with many alternatives.
Basically it has following parts :

  • switch keyword contains the expression.
  • case keyword- it is defined in switch block which holds some expression value and a colon. It defines some statements which is executed if it has the switch expression value.
  • break - It is used with each case statements to terminate the current case execution.
  • default -If no case value matches to the switch expression value, the default block executed.

Example :

In this example we are using switch -case statement to print the day of week. If day value is 1 then case 1 will execute its statement that is it will assign Sunday to String variable 'days' and use break to jump out the switch block. In the same way it works for day value 2,3..up to 7 to assign days value Monday, Tuesday...up to Saturday. We have written default at the last of all case statement which will execute when day value will not match to any cases. Finally the print statement prints the value of executed case. Here we have given day =6 so the case 6 will execute its statement and it will print Saturday.

package decisionMaking;

class SwitchStatement{
	public static void main(String[] args){
		int day = 6;
		String days;
		switch (day) {
		case 1:
		days = "Monday";
		break;
		case 2:
		days = "Tuesday";
		break;
		case 3:
		days = "Wednesday";
		break;
		case 4:
		days = "Thursday";
		break;
		case 5:
		days = "Friday";
		break;
		case 6:
		days = "Saturday";
		break;
		case 7:
		days = "Sunday";
		break;
		default:
		days = "Invalid day";
		break;
		}
		System.out.println("Day : " + days);
	
	}
}

Output :

Day : Saturday