3. Control Statements
3.1. if-else
1int a = 10;
2int b = 9;
3
4if (a < b) {
5 System.out.println("a < b");
6} else {
7 System.out.println("a >= b");
8}
3.2. if-elseif-else
1int a = 9;
2
3if (a > 20) {
4 System.out.println("a > 20");
5} else if (a > 10) {
6 System.out.println("a > 10");
7} else {
8 System.out.println("a <= 10");
9}
3.3. Nested if-else
1int a = 9;
2
3if (a > 20) {
4 System.out.println("a > 20");
5} else if (a > 10) {
6 System.out.println("a > 10");
7} else {
8 if (a > 5) {
9 System.out.println("a > 5");
10 } else {
11 System.out.println("a <= 5");
12 }
13}
3.4. switch
1char grade = 'B';
2
3switch (grade) {
4 case 'A':
5 System.out.println("great job!");
6 break;
7 case 'B':
8 System.out.println("good job!");
9 break;
10 case 'C':
11 System.out.println("let's do better!");
12 break;
13 case 'D':
14 System.out.println("need serious improvement!");
15 break;
16 default:
17 System.out.println("ouch!");
3.5. Nested switch
1int ethnicity = 1;
2String gender = "female";
3
4switch (ethnicity) {
5 case 0:
6 switch (gender) {
7 case "male":
8 System.out.println("white male");
9 break;
10 default:
11 System.out.println("white female");
12 }
13 case 1:
14 switch (gender) {
15 case "male":
16 System.out.println("minority male");
17 break;
18 default:
19 System.out.println("minority female");
20 }
21}
3.6. Arrow syntax for switch
Modern switch statements can use arrow labels. This avoids accidental
fall-through between cases.
1char grade = 'B';
2
3switch (grade) {
4 case 'A' -> System.out.println("great job!");
5 case 'B' -> System.out.println("good job!");
6 case 'C' -> System.out.println("let's do better!");
7 case 'D' -> System.out.println("need serious improvement!");
8 default -> System.out.println("ouch!");
9}
3.7. Switch expressions
Modern switch can also produce a value. This works well when each branch
chooses one result and the rest of the method should keep moving. Use
yield when a branch needs a block with more than one statement.
1char grade = 'B';
2
3String feedback = switch (grade) {
4 case 'A' -> "great job!";
5 case 'B' -> "good job!";
6 case 'C' -> "let's do better!";
7 case 'D' -> "need serious improvement!";
8 default -> {
9 String message = "unknown grade: " + grade;
10 yield message;
11 }
12};
13
14System.out.println(feedback);
JDK 26 previews primitive patterns in switch. Keep those examples in the
JDK 26 preview notes until the feature is final.