Skip to content

Java Control Flow – The Brain Behind Your Code

πŸ“Œ Why Control Flow Matters

Control flow allows your program to make decisions and repeat actions based on conditions. It’s the difference between a static app and one that responds to inputs and logic.

🧠 Conditional Statements

βœ… if Statement

int age = 18;
if (age >= 18) {
    System.out.println("You're eligible to vote.");
}

βœ… if...else

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

βœ… if...else if...else

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

βœ… switch Statement

Use when you have many conditions based on a single variable.

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("Another day");
}

πŸ” Loops – Repeating Tasks

πŸ” for Loop

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

πŸ” while Loop

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

πŸ” do...while Loop

Runs at least once before checking the condition.

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

πŸ”„ break and continue

πŸ”Ή break: Exits the loop

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

πŸ”Ή continue: Skips the current iteration

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

🎯 Practice Example

public class LoopPractice {
    public static void main(String[] args) {
        for (int i = 10; i >= 1; i--) {
            if (i % 2 == 0) continue;
            System.out.println("Odd number: " + i);
        }
    }
}

βœ… What You Learned

  • if, else, else if, and switch for decision-making
  • for, while, and do...while for loops
  • Using break and continue effectively

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *