Java

Explain Control Flow Statements in Java with Syntax and Example Code

By Utility Zone · 2025-11-06T11:37:35.087367

Control flow statements determine the order in which code is executed by directing program flow based on conditions, repetition, or explicit jumps. Java provides three main categories of control flow statements: conditional statements for decision-making, looping statements for iteration, and jump statements for altering execution flow.1

Classification of Java control flow statements into conditional, looping, and jump statements

Classification of Java control flow statements into conditional, looping, and jump statements


Conditional Statements (Decision Making)

Conditional statements enable your program to execute different blocks of code based on specific conditions.12

1. if Statement

The simplest conditional statement that executes code only if a condition is true.32

Syntax:2

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

Example:2

public class IfExample {
    public static void main(String[] args) {
        int age = 20;
        if (age >= 18) {
            System.out.println("You are an adult");
        }
    }
}

Output: You are an adult

2. if-else Statement

Provides an alternative code block to execute when the if condition is false.12

Syntax:3

if (condition) {
    // code block to be executed if condition is true
} else {
    // code block to be executed if condition is false
}

Example:2

public class IfElseExample {
    public static void main(String[] args) {
        int age = 15;
        if (age >= 18) {
            System.out.println("You can vote");
        } else {
            System.out.println("You cannot vote");
        }
    }
}

Output: You cannot vote

3. if-else-if Ladder

Tests multiple conditions sequentially and executes the first matching block.32

Syntax:3

if (condition1) {
    // execute some code only if condition1 evaluates to true
} else if (condition2) {
    // execute some code if condition2 evaluates to true
} else {
    // execute code if both conditions evaluate to false
}

Example:2

public class IfElseIfExample {
    public static void main(String[] args) {
        int score = 75;
        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");
        }
    }
}

Output: Grade: C

4. switch Statement

Selects one of many code blocks to execute based on a single expression value.324

Syntax:3

switch (expression) {
    case value1:
        // execute if expression equals value1
        break;
    case value2:
        // execute if expression equals value2
        break;
    default:
        // execute if no case matches
}

Important: The break statement exits the switch block. Without it, code falls through to the next case.4

Example:3

public class SwitchExample {
    public static void main(String[] args) {
        String language = "en";
        switch (language) {
            case "en":
                System.out.println("English");
                break;
            case "fr":
                System.out.println("French");
                break;
            case "de":
                System.out.println("Deutsch");
                break;
            default:
                System.out.println("Language not supported");
        }
    }
}

Output: English

When to use switch vs if-else:4

  • Use switch for testing a single value against multiple fixed options
  • Use if-else for range-based conditions or complex boolean logic

5. Ternary Operator (?:)

A compact replacement for simple if-else statements that returns a value based on a condition.25

Syntax:5

variable = condition ? expressionIfTrue : expressionIfFalse;

How it works:5

  • If the condition is true, expressionIfTrue is executed
  • If the condition is false, expressionIfFalse is executed

Example:65

public class TernaryExample {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int result = (num1 > num2) ? num1 : num2;
        System.out.println("Maximum: " + result);
        
        // Another example
        String status = (num1 > num2) ? "num1 is greater" : "num2 is greater";
        System.out.println(status);
    }
}

Output:

Maximum: 20
num2 is greater

Looping Statements (Iteration)

Looping statements enable repetitive execution of code blocks until a condition is no longer satisfied.1

1. for Loop

Used when you know exactly how many times to execute a code block.78

Syntax:8

for (statement1; statement2; statement3) {
    // code block to be executed
}
  • Statement 1: Initialization (executed once before the loop)
  • Statement 2: Condition (must be true to continue looping)
  • Statement 3: Increment/Decrement (executed after each iteration)

Example:7

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("Iteration " + i);
        }
    }
}

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

2. while Loop

Executes code repeatedly as long as a condition remains true.9

Syntax:

while (condition) {
    // code block to be executed
}

Example:9

public class WhileLoopExample {
    public static void main(String[] args) {
        int count = 0;
        while (count < 5) {
            System.out.println("Count: " + count);
            count++;
        }
        System.out.println("Loop finished");
    }
}

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Loop finished

3. do-while Loop

Executes the code block at least once, then checks the condition.10119

Syntax:10

do {
    // code block to be executed
} while (condition);

Key difference: The condition is checked after the first execution, guaranteeing at least one iteration.1110

Example:11

public class DoWhileExample {
    public static void main(String[] args) {
        int count = 1;
        do {
            System.out.println("GeeksforGeeks: " + count);
            count++;
        } while (count <= 5);
    }
}

Output:

GeeksforGeeks: 1
GeeksforGeeks: 2
GeeksforGeeks: 3
GeeksforGeeks: 4
GeeksforGeeks: 5

Practical use case: Menu-driven programs where you want to display a menu at least once before asking the user to quit.11

4. Enhanced for Loop (for-each)

Simplifies iteration through arrays and collections without managing indices.121314

Syntax:14

for (dataType variable : array) {
    // code to be executed
}

Example:13

public class EnhancedForExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}

Output:

1
2
3
4
5

Advantages:1213

  • Cleaner, more readable syntax
  • Automatically handles iteration without manual index management
  • Eliminates bounds-checking errors

Limitations:12

  • Cannot traverse in reverse order
  • Cannot skip elements or access indices

Jump Statements (Flow Control)

Jump statements alter the normal flow of program execution by skipping or terminating loops.151

1. break Statement

Immediately exits the loop or switch block, regardless of the condition.151617

Syntax:

break;

Example:16

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break;  // Exit loop when i equals 5
            }
            System.out.println(i);
        }
    }
}

Output:

0
1
2
3
4

Use case: Terminate a loop when a specific condition (like finding a value) is met.15

2. continue Statement

Skips the remaining statements in the current iteration and proceeds to the next iteration.151617

Syntax:

continue;

Example:16

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                continue;  // Skip even numbers
            }
            System.out.println("Odd number: " + i);
        }
    }
}

Output:

Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

Use case: Skip certain iterations based on a condition without terminating the loop.15

3. return Statement

Exits a method immediately and optionally returns a value to the caller.

Syntax:

return;           // No return value
return value;     // Return a value

Example:

public class ReturnExample {
    public static int findNumber(int[] arr, int target) {
        for (int num : arr) {
            if (num == target) {
                return num;  // Exit method and return the number
            }
        }
        return -1;  // Return -1 if not found
    }
    
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        System.out.println("Found: " + findNumber(numbers, 30));
    }
}

Output: Found: 30


Comprehensive Control Flow Example

public class ControlFlowDemo {
    public static void main(String[] args) {
        // Conditional: Grading system
        System.out.println("=== Grading System ===");
        int[] scores = {45, 78, 92, 88, 56};
        
        for (int score : scores) {
            String grade;
            if (score >= 90) {
                grade = "A";
            } else if (score >= 80) {
                grade = "B";
            } else if (score >= 70) {
                grade = "C";
            } else if (score >= 60) {
                grade = "D";
            } else {
                grade = "F";
            }
            System.out.println("Score: " + score + " → Grade: " + grade);
        }
        
        // Looping with break and continue
        System.out.println("\n=== Prime Numbers (1-20) ===");
        for (int i = 2; i <= 20; i++) {
            boolean isPrime = true;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.println(i + " is prime");
            }
        }
        
        // Switch and ternary operator
        System.out.println("\n=== Day of Week ===");
        int dayNumber = 3;
        String dayName;
        switch (dayNumber) {
            case 1: dayName = "Monday"; break;
            case 2: dayName = "Tuesday"; break;
            case 3: dayName = "Wednesday"; break;
            default: dayName = "Unknown";
        }
        String workDay = dayNumber >= 1 && dayNumber <= 5 ? "Weekday" : "Weekend";
        System.out.println("Day: " + dayName + " (" + workDay + ")");
    }
}

Output:

=== Grading System ===
Score: 45 → Grade: F
Score: 78 → Grade: C
Score: 92 → Grade: A
Score: 88 → Grade: B
Score: 56 → Grade: F

=== Prime Numbers (1-20) ===
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime

=== Day of Week ===
Day: Wednesday (Weekday)

Quick Reference Table

StatementPurposeWhen to Use
ifExecute code if condition is trueSingle condition check
if-elseChoose between two code blocksBinary decision
if-else-ifChoose among multiple optionsMultiple sequential conditions
switchChoose among many fixed valuesTesting single variable against many values
ternaryCompact conditional assignmentSimple condition with value assignment
forRepeat fixed number of timesKnown iteration count
whileRepeat until condition is falseUnknown iteration count
do-whileExecute at least once, then repeatNeed minimum one execution
for-eachIterate through collections/arraysIterating all array elements
breakExit loop/switch immediatelyTerminate on specific condition
continueSkip to next iterationSkip current iteration on condition
returnExit methodReturn control to caller

Understanding control flow statements is essential for writing conditional logic, iterating through data structures, and managing program execution in Java applications.12 <span style="display:none">181920</span>


<div align="center">⁂</div>

Footnotes

  1. https://www.slideshare.net/slideshow/control-flow-statements-in-java/60840921 ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  2. https://www.codingshuttle.com/blogs/java-flow-control/ ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11

  3. https://devqa.io/java-if-else-switch-statements/ ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  4. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html ↩ ↩2 ↩3

  5. https://www.geeksforgeeks.org/java/java-ternary-operator/ ↩ ↩2 ↩3 ↩4

  6. https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Java-Ternary-Operator-Nested-Examples-Return-if-else-symbol-void-null ↩

  7. https://www.freecodecamp.org/news/java-for-loop-example/ ↩ ↩2

  8. https://www.w3schools.com/java/java_for_loop.asp ↩ ↩2

  9. https://devqa.io/java-do-and-do-while-statements/ ↩ ↩2 ↩3

  10. https://www.w3schools.com/java/java_while_loop_do.asp ↩ ↩2 ↩3

  11. https://www.geeksforgeeks.org/java/java-do-while-loop-with-examples/ ↩ ↩2 ↩3 ↩4

  12. https://www.geekster.in/articles/java-for-loop/ ↩ ↩2 ↩3

  13. https://www.geeksforgeeks.org/java/difference-between-for-loop-and-enhanced-for-loop-in-java/ ↩ ↩2 ↩3

  14. https://www.freecodecamp.org/news/enhanced-for-loops-in-java-how-to-use-foreach-loops-on-arrays/ ↩ ↩2

  15. https://devqa.io/java-continue-break-statements/ ↩ ↩2 ↩3 ↩4 ↩5

  16. https://www.datacamp.com/doc/java/java-break-and-continue ↩ ↩2 ↩3 ↩4

  17. https://www.browserstack.com/guide/break-continue-in-java ↩ ↩2

  18. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator ↩

  19. https://runestone.academy/ns/books/published/csjava/Unit7-Arrays/topic-7-3-arrays-with-foreach.html ↩

  20. https://www.programiz.com/java-programming/for-loop ↩