Tag Archives: switch-case rule

Java: Switch Case Statement


The switch statement is a decision-making statement, also called a multi-way branch statement. It provides an easy way to jump execution to different parts of code based on the case value match with expression. This expression result allowed type as byte, short, char, and int primitive data types.

Note: After java 7+, it also allowed to work with enumerated types ( Enums in java), the String class and Wrapper classes.

Points to remember about Switch-Case statements

  • The value data type for a case must be the same data type as the variable in the switch.
  • The value for a case must be a constant or a literal.
    The value for the case, Variables are not allowed.
  • Duplicate case values are not allowed.
  • The break statement (optional) is used inside the switch to terminate a statement sequence.
  • If break statment is omitted, execution will continue on into the next case.
  • The default statement (optional) can appear anywhere inside the switch block. In case, if it is placed not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.

See Also :

Syntax:

switch(variable)
{
case 1:
   //execute your code
break;

case n:
   //execute your code
break;

default:
   //execute your code
break;
}

Note:

  • The switch statement is fast when compared with the case of multiple else if because it directly jumps to match condition.

Switch-Case Example

ublic class SwitchCaseTest {

	public static void main(String[] args){
		        int month = 5;
		        String monthString; 

		        // switch statement with int data type
		        switch (month) {
		        case 1:
		        	monthString = "January";
		            break;
		        case 2:
		        	monthString = "February";
		            break;
		        case 3:
		        	monthString = "March";
		            break;
		        case 4:
		        	monthString = "April";
		            break;
		        case 5:
		        	monthString = "May";
		            break;
		        case 6:
		        	monthString = "June";
		            break;
		        case 7:
		        	monthString = "July";
		            break;
		        case 8:
		        	monthString = "August";
		            break;
		        case 9:
		        	monthString = "September";
		            break;
		        case 10:
		        	monthString = "October";
		            break;
		        case 11:
		        	monthString = "November";
		            break;
		        case 12:
		        	monthString = "December";
		            break;
		        default:
		        	monthString = "Invalid Month";
		            break;
		        }
		        System.out.println("Selected Month "+month+" is "+monthString);
		    }
		}

Output


Selected Month 5 is May

 

Advertisements