int type = 3;
switch (type) {
case 1:
System.out.println("The type is 1");
break;
case 2:
System.out.println("The type is 2");
break;
case 3:
System.out.println("The type is 3");
break;
default:
System.out.println("Type not found");
}
Output
The type is 3
The switch can be used with Strings as well. (Starting from JDK 7)
String bloodGroup = "AB";
switch (bloodGroup) {
case "A":
System.out.println("Blood type: A");
break;
case "B":
System.out.println("Blood type: B");
break;
case "AB":
System.out.println("Blood type: AB");
break;
case "O":
System.out.println("Blood type: O");
break;
default:
System.out.println("Invalid blood type");
}
Output
Blood type: AB
This how to use the switch case with ‘char’ values
char grade = 'D';
switch (grade) {
case 'D':
System.out.println("Distinction");
break;
case 'C':
System.out.println("Credit");
break;
case 'P':
System.out.println("Pass");
break;
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Invalid grade");
}