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*/
1System.out.println(
2 switch (day) {
3 case MONDAY, FRIDAY, SUNDAY -> 6;
4 case TUESDAY -> 7;
5 case THURSDAY, SATURDAY -> 8;
6 case WEDNESDAY -> 9;
7 default -> throw new IllegalStateException("Invalid day: " + day);
8 }
9 );
1// syntax of switch statement in java
2switch(expression)
3{
4 case 1 value :
5 // code goes here
6 break;
7
8 case 2 value :
9 // code goes here
10 break;
11
12 case 3 value :
13 // code goes here
14 break;
15 .
16 .
17 .
18 .
19
20 default: // optional
21 // default code goes here
22}