Switch Statement in Java

A switch statement tests a variable for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
Syntax:

switch (expression) {
 case value1 :
 //Statements
 break; //optional
 case value2 :
 //Statements
 break; //optional
 //You can have any number of case statements.
 default : //Optional
 //Statements
}

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.When a break statement is reached, the switch terminates, and the flow of control jumps to the next line after the switch statement.Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

The example below tests month against a set of values and prints a corresponding message.

int month = 4;

switch(month) {
 case 1:
 System.out.println("January");
 break;
 case 2:
 System.out.println("February");
 break;
 case 3:
 System.out.println("March");
 break;
case 4:
 System.out.println("April");
 break;
}
// Output April

You can have any number of case statements within a switch. Each case is followed by the comparison value and a colon.A switch statement can have an optional default case. The default case can be used for performing a task when none of the cases is matched.

For example:

int month = 3;

switch(month) {
 case 6:
 System.out.println("June");
 break;
 case 7:
 System.out.println("July");
 break;
  default:
 System.out.println("Error");
}
// Outputs "Error"

No break is needed in the default case, as it is always the last statement in the switch.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s