1int day = 4;
2switch (day) {
3 case 6:
4 System.out.println("Today is Saturday");
5 break;
6 case 7:
7 System.out.println("Today is Sunday");
8 break;
9 default:
10 System.out.println("Looking forward to the Weekend");
11}
12// Outputs "Looking forward to the Weekend"
1// switch case in java example programs
2public class SwitchStatementExample
3{
4 public static void main(String[] args)
5 {
6 char grade = 'A';
7 switch(grade) {
8 case 'A' :
9 System.out.println("Distinction.");
10 break;
11 case 'B' :
12 case 'C' :
13 System.out.println("First class.");
14 break;
15 case 'D' :
16 System.out.println("You have passed.");
17 case 'F' :
18 System.out.println("Fail. Try again.");
19 break;
20 default :
21 System.out.println("Invalid grade");
22 }
23 System.out.println("Grade is: " + grade);
24 }
25}
1switch(x){
2 case(0): //if x == 0
3 //do some stuff
4 break;
5 //add more cases
6 default: //when x does not match any case
7 //do some stuff
8 break;
9}
1//the cooler looking edition (with input example)
2Scanner scn = new Scanner(System.in);
3int asd = scn.nextInt();
4
5switch(asd)
6{
7 case 1 -> System.out.println("case 1");
8 case 2 -> System.out.println("case 2");
9 case 5 -> System.out.println("case 5");
10 //case n...
11 default -> case 1 -> System.out.println("check out tunalad.bandcamp.com");
12}
13
14/* Output:
15asd = 1: "case 1"
16asd = 2: "case 2"
17asd = 5: "case 5"
18asd = 33213: "check out tunalad.bandcamp.com"
19*/
1A switch works with the byte, short, char, and int primitive data types.
2It also works with enumerated types (discussed in Enum Types), the String
3class, and a few special classes that wrap certain primitive types:
4Character , Byte , Short , and Integer (discussed in Numbers and Strings).
1For details about Java Switch tutorial visit website:
2https://www.allaboutjava.com/2021/07/java-switch-statements.html
3