Java Switch Statement

The switch statement allows the execution of different statements depending on the value of an expression. The switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with String class and few special classes that wrap certain primitive types. The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

Syntax

Switch ( control-expression){
case expression-1:
Statement-1
…
case expression-n:
Statement-n
…
default:
default Statements
}

Java Switch Statement | Switch case in java example programs

  • Control-expression is an expression of simple types, such as int, char, or an enum type. It can’t have a float or double type.

  • Expression-1, expression-n is the expression of a type that converts to the type of control expression. The compiler will look for these values as constant values.

  • Statement-1, statement-n is the sequence of statement that will be executed while expression matches with the case.

For example, here is a program to print the name of the day.

public class myswitchstatement{

	public static void main(String[] args) {

		int day = 3;
		String d = null;

		switch (day) {
		case 0:
			d = "SUNDAY";
			break;
		case 1:
			d = "MONDAY";
			break;
		case 2:
			d = "TUESDAY";
			break;
		case 3:
			d = "WEDNESDAY";
			break;
		case 4:
			d = "THURSDAY";
			break;
		case 5:
			d = "FRIDAY";
			break;
		case 6:
			d = "SATURDAY";
			break;
		default:
			d = "No Matching";
		}
		System.out.println("The Day Name is - " + d);
	}
}
Example Output

Using String in Switch Statement

In Java 7 and later, we can use a string object in the switch statement. The String in the switch expression is compared with the expressions associated with each case label.
If null String is evaluated in switch statement then it through NullPointerException.
For Example-

public class mytest {    
public static void main(String[] args) {    
   
    String lString="Expert";  
    int l=0;  
     
    switch(lString){    
     
    case "Beginner": l=100;  
    break;    
    case "Intermediate": l=250;  
    break;    
    case "Expert": l=302;  
    break;    
    default: l=0;  
    break;  
    }    
    System.out.println("Your Level is: "+l);  
}    
}
Example Output

Share