4. Control Statements

4.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}

4.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}

4.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}

4.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!");

4.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}

4.6. New syntax for switch

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}