All Posts

June 5, 2025

3 min read
JavaProgrammingControl FlowLoopsConditional Logic

Java Control Statements: Mastering Conditional Logic and Loops

Welcome back to the Java Fundamentals series! 👋

Conditional Statements

Conditional statements allow your program to make decisions based on different conditions. They're essential for creating dynamic, responsive applications that can handle various scenarios.

If Statement

The simplest form of conditional execution:

if (condition) {
    // code block executed if condition is true
}

Example:

int score = 85;
if (score >= 80) {
    System.out.println("Excellent performance!");
}

If-Else Statement

Provides an alternative path when the condition is false:

if (condition) {
    // executes if condition is true
} else {
    // executes if condition is false
}

Example:

int age = 17;
if (age >= 18) {
    System.out.println("You can vote!");
} else {
    System.out.println("Wait until you're 18 to vote.");
}

Important Points About If-Else:

  • ⚠️ Evaluation Order: Conditions are evaluated top-down. The first true condition's block runs.
  • ⚠️ Braces Matter: Without braces {}, each if or else controls only the immediate next statement.
  • ⚠️ Nested Pairing: Nested if-else pairs the nearest else with the nearest if unless braces clarify scope.
  • ⚠️ No Implicit Conversion: Java doesn't convert int to boolean - conditions must be boolean expressions.

If-Else-If Ladder

For multiple conditions, use the if-else-if ladder:

if (condition1) {
    // code block 1
} else if (condition2) {
    // code block 2
} else if (condition3) {
    // code block 3
} else {
    // default code block
}

Example:

int score = 92;
if (score >= 90) {
    System.out.println("Grade: A");
} else if (score >= 80) {
    System.out.println("Grade: B");
} else if (score >= 70) {
    System.out.println("Grade: C");
} else {
    System.out.println("Grade: F");
}

Switch Statement

The switch statement provides a cleaner alternative for multiple conditions based on a single variable:

switch (expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // default code
}

Example:

int dayOfWeek = 3;
switch (dayOfWeek) {
    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");
}

Key Switch Statement Features:

  • Fall-through Behavior: Unless you explicitly break, Java continues execution to subsequent cases
  • Control Flow: Control jumps to the matching case
  • Default Case: Runs if no matching case is found
  • Valid Types: byte, short, char, int, String (Java 7+), enum

⚠️ Warning: Fall-through can be both a feature (if intentional) and a common bug source!

Loops

For Loop

The most commonly used loop for definite iterations:

for (initialization; condition; update) {
    // code block
}

Example:

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

For Loop Components:

  • Initialization: Runs once before loop starts
  • Condition: Evaluated before every iteration
  • Update: Runs after each iteration

Advanced Example:

// Multiple variables (note: only one condition allowed)
for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println("i: " + i + ", j: " + j);
}

Enhanced For Loop (For-Each)

Perfect for iterating through collections and arrays:

for (type variable : collection) {
    // code block
}

Examples:

// Array iteration
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

// List iteration
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println("Hello, " + name);
}

While Loop

Executes as long as the condition remains true:

while (condition) {
    // code block
}

Example:

int count = 0;
while (count < 3) {
    System.out.println("Count: " + count);
    count++;
}

Do-While Loop

Guarantees at least one execution, then continues while condition is true:

do {
    // code block
} while (condition);

Example:

int userInput;
Scanner scanner = new Scanner(System.in);

do {
    System.out.print("Enter a positive number: ");
    userInput = scanner.nextInt();
    
    if (userInput <= 0) {
        System.out.println("Please enter a positive number!");
    }
} while (userInput <= 0);

System.out.println("Thank you! You entered: " + userInput);

When to Use Do-While:

  • Executes at least once regardless of condition
  • Useful for input validation and menu systems
  • Perfect when you need to perform an action before deciding whether to continue

Flow Control: Break and Continue

Break Statement

Exits the nearest enclosing loop or switch statement:

break; // exits the nearest loop or switch

Example:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // exits loop when i equals 5
    }
    System.out.println(i); // prints 0, 1, 2, 3, 4
}

Nested Loop Example:

outerLoop: for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (i == 1 && j == 1) {
            break outerLoop; // breaks out of both loops
        }
        System.out.println("i: " + i + ", j: " + j);
    }
}

Continue Statement

Skips the current iteration and continues with the next:

continue; // skips the current iteration and continues with the next

Example:

for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // skips when i equals 2
    }
    System.out.println(i); // prints 0, 1, 3, 4
}

Best Practices and Tips

1. Always Use Braces

// ❌ Avoid this - unclear and error-prone
if (condition)
    doSomething();
    doSomethingElse(); // This always executes!

// ✅ Use this - clear and safe
if (condition) {
    doSomething();
    doSomethingElse();
}

2. Prefer Enhanced For Loop When Possible

// ❌ Traditional loop
for (int i = 0; i < array.length; i++) {
    process(array[i]);
}

// ✅ Enhanced for loop (cleaner and less error-prone)
for (int element : array) {
    process(element);
}

3. Use Switch for Multiple Discrete Values

// ❌ Long if-else chain
if (status.equals("PENDING")) {
    // handle pending
} else if (status.equals("APPROVED")) {
    // handle approved
} else if (status.equals("REJECTED")) {
    // handle rejected
}

// ✅ Switch statement (cleaner)
switch (status) {
    case "PENDING":
        // handle pending
        break;
    case "APPROVED":
        // handle approved
        break;
    case "REJECTED":
        // handle rejected
        break;
}

Conclusion

  • ✅ Make decisions with if-else and switch statements
  • ✅ Execute code repeatedly with loops (for, while, do-while)
  • ✅ Control loop execution with break and continue
  • ✅ Write clean, readable, and maintainable code

I hope this guide helps you as much as creating it has helped me solidify these important concepts.

Happy coding! 💻