Control flow statements decide the order in which instructions are executed in a program.


1. Conditional Statements

✅ if Statement

int age = 18;
if (age >= 18) {
    System.out.println("You are an adult");
}

✅ if-else

if (age >= 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}

✅ if-else-if ladder

int marks = 85;
if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else {
    System.out.println("Grade C");
}

✅ switch-case

int day = 3;
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    case 3: System.out.println("Wednesday"); break;
    default: System.out.println("Invalid Day");
}

📌 Note: From Java 14, switch supports arrow syntax:

switch (day) {
    case 1 -> System.out.println("Monday");
    case 2 -> System.out.println("Tuesday");
    default -> System.out.println("Invalid");
}

2. Looping Statements

✅ for loop

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

✅ while loop

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

✅ do-while loop

Executes at least once.

int j = 1;
do {
    System.out.println(j);
    j++;
} while (j <= 5);

✅ for-each loop (enhanced for loop)

int[] arr = {10, 20, 30};
for (int num : arr) {
    System.out.println(num);
}

3. Jump Statements

✅ break

Used to exit a loop/switch early.

for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    System.out.println(i);
}

✅ continue

Skips the current iteration, moves to the next.

for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}

✅ return

Exits from a method.

public static int add(int a, int b) {
    return a + b;
}

4. Interview Tips

  • switch works with: int, char, String (Java 7+), enums.
  • Prefer for-each loop when you don’t need index.
  • Be careful with infinite loops (while(true)).
  • break vs continue → popular short question.
  • return is not only for loops but also exits methods.

End of Chapter 6 → You now understand decision-making and loops.
Next: Chapter 7 Arrays in Java (1D, 2D, common problems).