Java Control Flow Statements

When a Java program is executed, it is executed statement by statement. Generally, all statements are executed sequentially from top to bottom. Sometimes, to apply business logic, we may need to execute statements conditionally, based on the result of an expression evaluation.

Control flow statements help in the conditional execution of specific statements. All control flow statements are associated with a business condition – when true, the code block executes; when false it is skipped.

In Java, a control flow statement can be one of the following:

1. Selection Statement

Selection statements are based on an expression evaluation. If the evaluation is true then execute a block, else execute another block.

1.1. if-else Statement

The if-else statement tells the program to execute a certain section of code only if a particular test evaluates to true otherwise else block is executed.

boolean condition = true;

if(condition) {
    System.out.println("Condition is true");    //This statement is executed
} else {
    System.out.println("Condition is false");

We can have nested if-else blocks.

int i = 5;

if(i < 0) {
    System.out.println("Value of 'i' is Negative.");
} else if(i > 0 && i < 100) {
    System.out.println("Value of 'i' is Less Than 100.");   //This statement is executed 
} else {
    System.out.println("Value of 'i' is Greater Than 100.");

1.2. switch…case Statement

As if-else statement tells the program to execute a certain section of code only if a particular test evaluates to true or false, the switch statement can have multiple execution paths.

The switch…case statement forks the execution flow based on the value of the variable. The break statement allows the switch…case statement to be executed properly else all cases will be executed.

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, String, and wrapper classes.

String value = "B";
switch (value) 
        case "A":
                System.out.println("Value is A");
        case "B": 
                System.out.println("Value is B");    //This case is executed
                System.out.println("Value is neither A nor B");

Since Java 14, we can write the above switch statement in a less verbose manner.

String value = "B";

switch (value) {
  case "A"  -> System.out.println("Value is A");
  case "B"  -> System.out.println("Value is B");
  default    -> System.out.println("Value is neither A nor B");

2. Iteration Statement

2.1. while Loop

The while loop statement continually executes a block of statements while a particular condition is true. The while statement continues testing the expression and executing the block until the expression evaluates to false.

int count = 1;
while (count < 5) 
  System.out.println("Count is: " + count);   // 1 2 3 4 5

2.2. do-while Loop

The difference between do-while and while statements is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

Note that the do-while statement ends with a semicolon. The condition-expression must be a boolean expression.

int i = 1;
int sum = 0;
    sum = sum + i;
while (i <= 10);

2.3. for Loop

The for loop statement iterates repeatedly over a range of values until a particular condition is satisfied.

for(int num = 1; num <= 5; num++) {

Java 5 introduced an foreach loop, which is called a enhanced for-each loop. It is used for iterating over elements of arrays and collections.

int[] numList = {10, 20, 30, 40};
for(int num : numList) 

3. Exception Handling Statement

In Java, exception classes are used to represent events that disrupt the normal execution flow. Their names typically end with Exception – such as NullPointerException or IOException.

The exception instances can be generated (thrown) either automatically by the JVM or by the application code, using the throw keyword. The try-catch or try-catch-finally constructs are used to capture the thrown exception object and redirect the execution flow to another branch of code. If the thrown exception is not caught, it propagates all the way out to the JVM and forces it to exit.

3.1. try-catch-finally Statement

The exception object thrown from a try block is captured in the corresponding catch block. The code in the finally block is always executed and usually contains the code to release the expensive resources held by the application code.

try {
  //open file
    //read file
catch(Exception e) {
    //handle exception while reading the file
finally {
  //close the file

3.2 throw Statement

The throw statement is used to throw an exception object from the application code manually.

    throw new NullPointerException("Null occurred");
catch (Exception e) 
    System.out.println("catch block");

4. Branching Statement

Branching statements allow the breaking of the current execution flow and continuation of execution from the start of the block, the end of the block, or a certain (labeled) point of the control flow.

4.1. break Statement

The break keyword is used to terminate forwhile, or do-while loops. It may also be used to terminate a switch statement as shown in the previous sections.

  //loop statements

4.2. continue Statement

continue statement can only be used inside the forwhile, and do-while loops. The continue statement skips the statements after it and starts the new iteration in the loop.

for( int i = 0 ; i < 10 ; i++ ) {
  if( i % 2 == 0) {        
    continue;    //if i is even, skip the print statement
  System.out.println("The number is " + i );

4.3. Labeled Statement

Whenever a labeled break statement is encountered during program execution, then the control immediately goes out of the enclosing labeled block. Similarly, labeled continue will bring control back to the start.

The labeled statements are similar to break and continue statements, with additional names given to the blocks.

while (Some condition)
  if ( a specific condition )
  		break hackit;       //label
  		//normal business logic goes here..

4.4. yield Keyword

The yield is added in Java 14, and is used inside switch expressions. A yield statement transfers control by causing an enclosing switch expression to produce a specified value.

      yield Expression;

Let us understand with a simple example. In the following example, switch expression is returning a boolean value. The value is true if it is a weekday, else value is false.

Boolean result = switch(day) 
  case MON, TUE, WED, THUR, FRI ->
    System.out.println("It is WeekDay");
    yield true; 
  case SAT, SUN ->
    System.out.println("It is Weekend");
    yield false; 
System.out.println("Result is " + result);

5. Conclusion

In this tutorial, we learned the control flow statements available in Java for controlling the program execution. We learned how the conditional expression evaluation determines which block will be executed based on the evaluation result.

Happy Learning !!

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial