switch statement in Java

A switch statement enables a programmer to select one of the execution paths based on the value of an expression. It is very much similar to if-else if statement that we studied previously.

  • A switch statement has one or more case labels and a single default label.
  • A default label is executed when no matching value is found in the case labels.
  • The argument of switch() must be one of the following types- byte, short, char, int or enum.
  • You cannot have duplicate case labels, that is the same value cannot be used twice.
  • The default label does not have to be placed at the end. It can appear anywhere in the switch block.

Working of switch statement

Let's start from the top of the switch block, each non-default case is checked. If the case gives true, the statements in that case and the following cases are executed until a break statement is encountered. If none of the non-default cases is true, and the execution control meets with the default case, the statements in the default case and all the following cases are executed until a break statement is encountered.

Syntax

switch(variable)
{
	case value1:
		//code to be executed
		break;
	case value2:
		//code to be executed
		break;
	...
	case valuen:
		//code to be executed
		break;
	default:
		//code to be executed
		break;
}

Flowchart of switch statement

Switch statement in Java

Example

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

Output

Tuesday