Flow Control in Java: Master Decision Making and Loops

Flow Control

Every Java program contains multiple statements. But have you ever wondered:

"In what order are these statements executed?"

The answer is Flow Control.

Flow Control decides the execution order of statements during runtime.

🔥 What is Flow Control in Java?

Flow Control is the mechanism that controls the order in which statements execute in a Java program.

Based on conditions and requirements Java decides whether to:

  • Execute a block of code
  • Skip a block of code
  • Repeat a block of code
  • Transfer control to another statement

📌 Types of Flow Control Statements

1️⃣ Selection Statements

  • if-else
  • switch

2️⃣ Iterative Statements

  • while
  • do-while
  • for
  • for-each (Java 1.5)

3️⃣ Transfer Statements

  • break
  • continue
  • return
  • try-catch-finally
  • assert

1. Selection Statements

Selection statements are used when we want to execute different blocks of code based on conditions.

Java provides two selection statements:

  • if-else
  • switch

1.1 if-else Statement

The if-else statement executes one block when the condition is true and another block when the condition is false.

Syntax:

if(condition)
{
    statement;
}
else
{
    statement;
}

⚠️ Condition Rule

The condition inside if statement must always be of boolean type.

Only true or false values are allowed.

Example 1: Using int in if condition

int x = 0;

if(x)
{
    System.out.println("hello");
}
else
{
    System.out.println("hi");
}
Compile Time Error:

incompatible types:
found: int
required: boolean
Remember:

In C and C++, integer values can be used as conditions.

But Java strictly allows only boolean values.

Example 2: Assignment inside if condition

boolean b = true;

if(b = false)
{
    System.out.println("hello");
}
else
{
    System.out.println("hi");
}
Output:

hi
Explanation:

First assignment executes:

b = false;

The condition becomes false, so the else block executes.

Example 3: Comparison using ==

boolean b = false;

if(b == false)
{
    System.out.println("hello");
}
else
{
    System.out.println("hi");
}
Output:

hello

📌 Curly Braces and else are Optional

If we want to execute only one statement, curly braces are optional.

Valid:

if(true)
    System.out.println("hello");

Invalid:

if(true)
    int x = 10;
Declaration statement is not allowed without curly braces.

🚫 Dangling Else Problem

Java does not have a dangling else problem.

if(true)
    if(false)
        System.out.println("hello");
    else
        System.out.println("hi");
Output:

hi

The else statement always belongs to the nearest unmatched if statement.

1.2 Switch Statement

When we have multiple options available, using multiple if-else statements reduces code readability.

In such situations, the switch statement is recommended.

Switch allows us to select and execute one block of code from multiple choices.

Syntax of Switch:

switch(expression)
{

    case value1:
        statement;
        break;


    case value2:
        statement;
        break;


    default:
        statement;

}

📌 Allowed Data Types in Switch

The expression used inside switch supports only specific data types.

  • byte
  • short
  • int
  • char
  • String (Java 1.7 onwards)
  • enum
  • Wrapper classes: Byte, Short, Integer, Character (Java 1.5 onwards)
Important:

Switch is the only flow control statement where curly braces { } are mandatory.

📌 Case and Default Rules

  • case labels are optional
  • default case is optional
  • But every statement inside switch must belong to either a case or default block.

Example: Statement without case

int x = 10;


switch(x)
{

    System.out.println("hello");

}
Compile Time Error:

Every statement inside switch must be associated with case or default.

📌 Expressions in Switch

Both switch expression and case labels can be expressions.

But the important rule is:

Case labels must be constant expressions.

Example 1: Variable as Case Label

int x = 10;

int y = 20;


switch(x)
{

    case 10:
        System.out.println("hello");
        break;


    case y:
        System.out.println("hi");
        break;

}
Compile Time Error:

Constant expression required.

Because y is not a constant value.
If y is declared as final, then it becomes valid.

Example 2: Constant Expression

int x = 10;


switch(x + 1)
{

    case 10:
        System.out.println("hello");
        break;


    case 10 + 20 + 30:
        System.out.println("hi");
        break;

}
Valid Code

Both switch expression and case labels can be expressions.
Case label must be a constant expression.

📌 Case Label Range Checking

The value of a case label must be within the range of the switch argument data type.

Example 1:

byte b = 10;


switch(b)
{

    case 10:
        System.out.println(10);
        break;


    case 100:
        System.out.println(100);
        break;


    case 1000:
        System.out.println(1000);
        break;

}
Compile Time Error:

Possible loss of precision.

Found : int
Required : byte

Example 2:

byte b = 10;


switch(b + 1)
{

    case 10:
        System.out.println(10);
        break;


    case 100:
        System.out.println(100);
        break;


    case 1000:
        System.out.println(1000);
        break;

}
Valid Code

Because b + 1 becomes int after promotion.

❌ Duplicate Case Labels

Duplicate case labels are not allowed inside switch.

Example:

int x = 10;


switch(x)
{

    case 97:
        System.out.println(97);
        break;


    case 100:
        System.out.println(100);
        break;


    case 'a':
        System.out.println(97);
        break;

}
Compile Time Error:

Duplicate case label.

Because character 'a' has ASCII value 97.

🔥 Fall Through Inside Switch

If we do not write break statement, execution continues into the next case.

switch(x)
{

    case 0:
        System.out.println(0);


    case 1:
        System.out.println(1);
        break;


    case 2:
        System.out.println(2);


    default:
        System.out.println("def");

}
When x = 0

0
1


When x = 1

1


When x = 2

2
def


When x = 3

def

📌 Default Case in Switch

  • Default executes when no matching case is found.
  • Default can be written anywhere inside switch.
  • Recommended practice is writing default at the end.
  • Default executes maximum one time.

Example:

switch(x)
{

    default:
        System.out.println("def");


    case 0:
        System.out.println(0);
        break;


    case 1:
        System.out.println(1);
        break;


    case 2:
        System.out.println(2);

}
When x = 0
0

When x = 1
1
2

When x = 2
2

When x = 3
def
0

♻️ Switch Code Reusability

Multiple cases can execute the same block of code.

switch(x)
{

    case 0:

    case 1:

    case 2:

        System.out.println("Q1");
        break;



    case 3:

    case 4:

    case 5:

        System.out.println("Q2");
        break;

}

2. Iterative Statements (Loops)

Iterative statements are used to execute a block of code repeatedly until a particular condition becomes false.

In simple words:

Loops help us execute the same code multiple times without rewriting it.

Java provides four types of iterative statements:

  • while loop
  • do-while loop
  • for loop
  • for-each loop

2.1 while Loop

The while loop is suitable when the number of iterations is not known in advance.

It first checks the condition and executes the body only when the condition is true.

Syntax:

while(condition)
{

    statement;

}

📌 Condition Rule in while Loop

The condition inside while loop must always be of boolean type.

Other data types are not allowed.

Example: Using int in while condition

while(1)
{

    System.out.println("hello");

}
Compile Time Error:

Incompatible types:
found: int
required: boolean

📌 Curly Braces in while Loop

Curly braces are optional in while loop.

Without curly braces, only one statement is allowed.

That statement should not be a declaration statement.

Example 1:

while(true)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code
Because while(true) creates an infinite loop, the statement after the loop can never execute.

Example 2:

while(false)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code

Example 3:

int a = 10;

int b = 20;


while(a < b)
{

    System.out.println("hello");

}


System.out.println("hi");

Valid Code

The condition is not evaluated at compile time.
JVM checks it during runtime.

Example 4:

int a = 10;

int b = 20;


while(a > b)
{

    System.out.println("hello");

}


System.out.println("hi");

Valid Code

Condition is checked during runtime.

Example 5: Using final variables

final int a = 10;

final int b = 20;


while(a < b)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code
Because final variable values are replaced during compilation. The compiler already knows the condition result.

Example 6:

final int a = 10;

final int b = 20;


while(a > b)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code

2.2 do-while Loop

The do-while loop is different from while loop because it executes the body at least once.

The condition is checked only after executing the loop body.

Syntax:

do
{

    body;

}

while(condition);

Important:

The semicolon (;) after while condition is mandatory in do-while loop.

📌 Condition Rule in do-while

  • Condition must be boolean type.
  • Curly braces are optional.
  • Without braces only one non-declarative statement is allowed.

Example 1:

do
{

    System.out.println("hello");

}

while(true);


System.out.println("hi");

Compile Time Error:

Unreachable code

Example 2:

do
{

    System.out.println("hello");

}

while(false);


System.out.println("hi");

Output:

hello
hi
The hello statement executes because do-while executes the body at least once.

Example 3:

int a = 10;

int b = 20;


do
{

    System.out.println("hello");

}

while(a < b);


System.out.println("hi");

Output:

hello
hello
hello
.....

Infinite times
Because a and b are not final variables, their values are not replaced during compilation.

Example 4:

int a = 10;

int b = 20;


do
{

    System.out.println("hello");

}

while(a > b);


System.out.println("hi");

Output:

hello
hi

Example 5: Using final variables

final int a = 10;

final int b = 20;


do
{

    System.out.println("hello");

}

while(a < b);


System.out.println("hi");

Compile Time Error:

Unreachable code

Example 6:

final int a = 10;

final int b = 20;


do
{

    System.out.println("hello");

}

while(a > b);


System.out.println("hi");

Output:

hello
hi

2.3 for Loop

The for loop is the best choice when the number of iterations is known in advance.

It contains three parts:

  • Initialization
  • Condition checking
  • Increment / Decrement

Syntax:

for(initialization; condition; increment/decrement)
{

    body;

}

📌 Curly Braces in for Loop

Curly braces are optional in for loop.

Without curly braces only one statement is allowed.

That statement should not be a declaration statement.

Example 1:

for(int i = 0; true; i++)
{

    System.out.println("hi");

}

Valid Code

Example 2:

for(int i = 0; i < 10; i++);

Valid Code

Empty statement is allowed.

Example 3:

for(int i = 0; i < 10; i++)

    int x = 10;

Compile Time Error:

Declaration statement is not allowed without curly braces.

📌 Initialization Section

  • Initialization section is optional.
  • We can declare multiple variables of the same type.

Valid Example:

for(int i = 0, j = 0; i < 5; i++)
{

    System.out.println(i);

}

Valid because both variables are integers.

Invalid Example:

for(int i = 0, String s = "hello"; i < 5; i++)
{

}

Compile Time Error

Different data types cannot be declared together.

Another Invalid Example:

for(int i = 0, int j = 0; i < 5; i++)
{

}

Compile Time Error

We should not write data type again.

📌 Condition Section

  • Condition is optional.
  • Condition must always return boolean value.
  • If condition is missing, compiler automatically places true.

Example:

for(;;)
{

    System.out.println("hello");

}

Output:

hello hello hello.....

Infinite times

📌 Increment / Decrement Section

Increment or decrement section can contain any valid Java statement.

Example:

int i = 0;


for(System.out.println("hello"); i < 3; System.out.println("hi"))
{

    i++;

}

Valid Code

🔥 All Three Parts of for Loop are Optional

Initialization, condition and increment/decrement sections are independent.

All three can be skipped.

📌 for Loop Examples

Example 1:

for(int i = 0; true; i++)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code

Example 2:

for(int i = 0; false; i++)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code

Example 3:

for(int i = 0; ; i++)
{

    System.out.println("hello");

}


System.out.println("hi");

Compile Time Error:

Unreachable code

Example 4:

int a = 10;

int b = 20;


for(int i = 0; a < b; i++)
{

    System.out.println("hello");

}

hello.....
Infinite times

Example 5:

int a = 10;

int b = 20;


for(int i = 0; a > b; i++)
{

    System.out.println("hello");

}


System.out.println("hi");

hi

2.4 Enhanced for Loop (for-each Loop)

Enhanced for loop was introduced in Java 1.5.

It is specially designed to access elements from:

  • Arrays
  • Collections

Syntax:

for(dataType variable : array/collection)
{

    statement;

}

Example 1: Printing 1D Array Elements

int[] arr = {10,20,30,40,50};


for(int x : arr)
{

    System.out.println(x);

}

Output:

10
20
30
40
50

Example 2: Printing 2D Array Elements

int[][] arr = {

    {10,20},

    {30,40,50}

};


for(int[] x1 : arr)
{

    for(int x : x1)
    {

        System.out.println(x);

    }

}

Output:

10
20
30
40
50

🎯 Flow Control Interview Points

  • if condition accepts only boolean values.
  • switch supports byte, short, int, char, String, enum and wrapper classes.
  • Case labels must be constant expressions.
  • Duplicate case labels are not allowed.
  • while checks condition before execution.
  • do-while executes at least once.
  • for loop is preferred when iteration count is known.
  • Enhanced for loop is mainly used with arrays and collections.

🏁 Conclusion

Flow Control statements are the foundation of decision making and repetition in Java programs.

A strong understanding of conditions and loops helps you write efficient Java applications.

After learning Flow Control, the next important step is understanding how Java handles text data.

📚 Explore More Java Blogs

Continue your Java learning journey with my complete Java series:

👉 Visit Roadmap For Java

Comments

Popular posts from this blog

Java Roadmap

Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-2)

Identifiers