Java Flow Control: A guide to understand the If-else and Loops in Java

    Java Flow Control: A guide to understand the If-else and Loops in Java

    This article provides an in-depth exploration of Java flow control statements, covering decision-making, looping, and branching mechanisms. With clear explanations, syntax examples, and practical applications, it serves as a valuable resource for both beginners and experienced developers aiming to enhance their Java programming skills.

    default profile

    Shreya Adak

    February 14, 2025

    8 min read

    Introduction:#

    In Java, flow control statements dictate the order in which instructions are executed, enabling developers to manage the program's execution path based on specific conditions or repetitions. These statements are fundamental for implementing your code's decision-making, looping, and branching mechanisms.

    Flow Control

    1. Decision-Making Statements (Conditional Statements):#

    Conditional Statements

    In Java, decision-making statements help to control the flow of execution based on certain conditions. These statements evaluate the expressions and execute the different code blocks depending on whether the conditions are true or false.

    Condition

    a. if Statement:#

    It evaluates a boolean expression; if true, executes the associated block of code.

    public class FlowControlStatements { public static void main(String[] args) { boolean condition = true; if(condition) System.out.println("Hi"); } }

    b. if-else Statement:#

    Provides an alternative path if the if condition evaluates to false.

    public class FlowControlStatements { public static void main(String[] args) { boolean condition = false; if(condition) System.out.println("Hi"); else System.out.println("Hello"); } }

    c. if-else-if Ladder:#

    Chains multiple conditions; executes the block where the condition is true.

    public class FlowControlStatements { public static void main(String[] args) { int condition = 9; if(condition > 10) System.out.println("Yes! condition > 10"); else if (condition > 0) System.out.println("Yes! condition > 0"); else System.out.println("Yes! condition < 0"); } }

    d.switch Statement:#

    It allows the selection among multiple options based on the value of an expression.

    public class FlowControlStatements { public static void main(String[] args) { int condition = 1; switch (condition){ case 1: System.out.println("condition = 1"); break; case 2: System.out.println("condition = 2"); break; default: System.out.println("condition > 1 and condition > 2"); } } }

    Ternary Operator: It is used to evaluate a test condition and executes a block of code based on the result of the condition. This operator replaces certain types of if-else statements.

    Syntax: 

    Ternary Operator
    public class FlowControlStatements { int condition = 1; boolean TernaryOperation() { return condition == 1 ? true : false; } public static void main(String[] args) { FlowControlStatements obj = new FlowControlStatements(); if(obj.TernaryOperation()) System.out.println("True"); else System.out.println("False"); } }

    2. Looping Statements (Iteration Statements):#

    1. Initialization Expression(s)
    2. Test Expressions (Conditions)
    3. Body of the Loop
    4. Update Expressions
    Looping

    Looping statements in Java allow executing a code block multiple times until a specified condition is met. This helps in reducing redundancy and improving efficiency in programs.

    a.for Loop:#

    The traditional for loop is used when we need explicit control over the loop index. It is useful for iterating over an array or a list where we may need to modify elements or access specific indices.

    For loop

    Syntax:

    For loop Syntax
    public class FlowControlStatements { public static void main(String[] args) { int n = 10; for(int i=0; i<n; i++){ System.out.println(i); } } }

    Output:

    For loop Output

    b. Enhanced for Loop (for-each):#

    Introduced in Java 5, the for-each loop is a simplified way of iterating over arrays and collections. It does not require an index and is read-only (modifications to elements are not possible directly).

    Syntax:

    for-each loop
    public class FlowControlStatements { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int num : numbers) { System.out.println(num); } } }

    Output:

    for-each output

    c. while Loop:#

    The condition is checked first before executing the loop body. If the condition is false initially, the loop body will not execute even once. It is an entry-controlled loop (checks condition before execution).

    while loop

    Syntax:

    while loop syntax
    public class FlowControlStatements { public static void main(String[] args) { int n = 10; int i = 0; while(i<n){ System.out.println(i); i++; } }

    Output:

    while loop output

    d. do-while Loop: (Executes Once Even if Condition is False)#

    The loop body executes first, then the condition is checked. Ensures that the loop executes at least once, even if the condition is false initially. It is an exit-controlled loop (checks condition after execution).

    do while loop output

    Syntax:

    do-while loop syntax
    public class FlowControlStatements { public static void main(String[] args) { int n = 10; int i = 10; do{ System.out.println(i); i++; }while(i<n); } }

    Output:

    do-while loop output

    Logical Operator: “AND” (&&), “OR”(||) and “NOT”(!) are ****used to perform logical operations. Relational Operator: “==”, “!=”, “>”, “<”, “>=”, “<=”, are ****used to check the relation between two operands.

    3. Jump Statements (Branching Statements):#

    Jump statements (also called branching statements) in Java control the flow of execution by transferring it to another part of the program.

    Branching

    a. break Statement (Exiting a Loop or Switch Case):#

    The break statement terminates the loop. (switch statement immediately).

    break

    Syntax:

    break syntax
    public class FlowControlStatements { public static void main(String[] args) { int n = 10; int i = 0; while(i<n){ if(i==5) break; else System.out.println("i != n"); i++; System.out.println(i); } System.out.println("Loop ended"); } }

    Output:

    break output

    b. continue Statement (Skip Current Iteration):#

    The continue statement skips the current iteration and moves to the next iteration of the loop.

    continue

    Syntax:

    continue syntax
    public class FlowControlStatements { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { if (i % 2 == 0) { continue; // Skips even numbers } System.out.println("Number: " + i); } } }

    Output:

    continue output

    Labeled Blocks (Labeled Break and Labeled Continue):#

    Labeled blocks in Java are advanced control flow techniques that allow breaking out of or continuing a specific loop when dealing with nested loops. A label in Java is an identifier followed by a colon (:) placed before a loop. It helps in controlling which loop should be affected by break or continue.

    labeled

    Labeled continue Statement: Used to skip the current iteration of a specific outer loop instead of the nearest one. Regular continue only affects the inner loop, but labeled continue affects the outer loop.

    public class FlowControlStatements { public static void main(String[] args) { outerLoop: // Label for outer loop for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { System.out.println("Skipping iteration for i=2"); continue outerLoop; // Skips rest of outer loop iteration } System.out.println("i: " + i + ", j: " + j); } } System.out.println("Loop finished!"); } }

    Output:

    Labeled continue  output

    Labeled break Statement: Used to terminate a specific outer loop instead of just the inner loop. Regular break only exits the nearest loop, but labeled break exits the labeled loop.

    public class FlowControlStatements { public static void main(String[] args) { outerLoop: // Label for outer loop for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.println("i: " + i + ", j: " + j); if (i == 2 && j == 2) { System.out.println("Breaking out of outer loop!"); break outerLoop; // Exits both loops } } } System.out.println("Loop finished!"); } }

    Output:

    Labeled break output

    c. return Statement (Exit from a Method):#

    The return statement terminates a method and optionally returns a value.

    public class FlowControlStatements { public static int square(int num) { return num * num; // Returns square of number } public static void main(String[] args) { int result = square(5); System.out.println("Square: " + result); } }

    Output:

    return Statement  output

    4. Exception Handling (Try-Catch-Finally):#

    try Block: Contains code that may throw an exception.

    catch Block: Handles specific exceptions that occur in the **try**block.

    finally Block: Executes always, whether an exception occurs or not.

    public class FlowControlStatements { public static void main(String[] args) { try { int result = 10 / 0; // Exception occurs } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero!"); } finally { System.out.println("Finally block always executes."); } } }

    Output:

    try-catch-finally

    Conclusion:#

    This article uses examples and syntax to explore Java flow control statements, including decision-making, looping, and branching mechanisms. Mastering these concepts enhances code efficiency, readability, and logical structuring in Java programming.

    Java
    Control flow
    labeled looping
    looping
    Conditional
    Branching

    More articles