Control Flow in Java: Directing Your Program’s Path

Control flow determines how your program decides what to do next based on conditions or repeated actions. Mastering control flow lets you create programs that make decisions, repeat tasks, and handle complex logic.

This post covers:

  • Conditional statements (if, else, switch)

  • Loops (for, while, do-while)

  • Break and continue statements


❓ Conditional Statements

1. if Statement

Executes a block of code only if a condition is true.

java
int age = 18;

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

2. if-else Statement

Defines an alternative block if the condition is false.

java
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}

3. if-else if-else Ladder

Checks multiple conditions in sequence.

java
if (age < 13) {
System.out.println("You are a child.");
} else if (age < 18) {
System.out.println("You are a teenager.");
} else {
System.out.println("You are an adult.");
}

4. switch Statement

Simplifies checking a variable against multiple constant values.

java
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");
}


Loops: Repeating Actions

1. for Loop

Repeats a block a set number of times.

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

2. while Loop

Repeats as long as a condition is true.

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

3. do-while Loop

Executes the loop body first, then checks the condition.

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

⏹️ Break and Continue

break

Exits the nearest enclosing loop immediately.

java
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i is 5
}
System.out.println(i);
}

continue

Skips the current iteration and continues with the next.

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

Example: Combining Control Flow

java
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
}

Summary

  • Use if, else, and switch to make decisions

  • Use loops (for, while, do-while) to repeat code

  • Use break and continue to control loop execution

Leave a Reply

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