Flow Control and Assertions in Java

by Vibrant Publishers

Introduction:

This blog will elaborate on the concept of flow control statements in Java. We will also take a look at the syntax of flow control statements, their flow charts, and assertions which are used to validate the correctness of assumptions in Java programming. 

 

 

Flow Control:

Flow Controls are a set of statements in Java that govern the order in which statements are executed in a running program.

Flow Control statements are mainly classified into three categories:

  • Selection statements: if, if-else & switch Iteration
  • Iteration statements: while, do-while & for.
  • Transfer statements: break, continue, return.

     

     

    1. Selection Statements:

    Selection statements are used in Java for selecting alternative actions during the execution of a program. The selection statements are:
     
    • Simple if statement:

     

    The simple if statement follows the syntax below:

     

     

    if (condition): {

     

    statement

     

    }

     

     

    These kinds of statements are useful when we have to decide whether an action is to be performed or not, based on a condition. The condition may be an integer value or float value and the action to be performed is based on this condition, which can be in the form of a single statement or a code block. They must evaluate a boolean value. That is, it should return either a True or False.

     

    The code flow is illustrated in the given activity diagram.

     

     


    • The if-else statement:

     

    The Java if-else statement is used to decide between two actions, based on a condition. It has the following syntax:

     

     

     

    if (condition1):

    {

    Statement1

    }

    else {

    Statement2

    }

     

     

    The code flow is illustrated in the given activity diagram.

     


    • The switch statement:

     

    The switch statement can be used to choose one action among many alternative actions, based on the value of a switch expression. In general, a switch case will be written as follows:

     

     

     

    switch ( ) {

    case label 1 :

    case label 2 :

    case label n :

    default:

    }

     

     

    2. Iteration Statements:

    Iteration statements or looping structures that allow a block of code to execute repeatedly. Java provides three iteration mechanisms for loop construction. They are as follows:

     

    • The while statement:

     

    The syntax will be as follows:

     

     

     

    while (condition);

     

    {

     

    statement

     

    }

     

     

    Here the condition of the while loop is evaluated first and then if the resulting value is True, the loop gets executed. On the other hand, if the condition is False, the loop is terminated and execution continues with the statement immediately following the loop block.

     

     

    • The do-while statement:

     

    The syntax is as follows:

     

     

     

    do {

    statement

    }

    while(Condition );

     

     

    Example:

     

     

     

    int i=1;

    do{

      System.out.println(i);

       i++;

    }while(i<=10);

     

     

    The above code block will print numbers 1 to 10 in a row. One thing to note here is that do loop is executed whenever the condition of the while loop is true. The activity diagram given below will explain the control flow:

     

     


    • The for( ; ; ) statement:

     

    It is mostly used for counter controlled loops where we already know the number of iterations needed to be made.

     

    The syntax is as given below:

     

     

     

    for (int;condition;increment/decrement)  // code to be executed

     

     

    The for( ; ; ) statement usually declares and initializes a loop variable that controls the execution of the loop. The output of the loop must be a boolean value. If the output is true, the loop body is executed, otherwise, execution continues with the statement following the for(;;) loop. After each iteration, the loop is executed, which will usually modify the value of the loop variable to ensure a loop termination. Note that this is only executed once on entry to the loop.

     

     
    • The enhanced for(:) statement:

     

    This for(:) statement, otherwise called the enhanced for loop structure, is convenient when we need to iterate over an array or a collection, especially when some operation needs to be performed on each element of the array or collection.The syntax for an enhanced for(:) loop is shown below.

     

     

     

    for (data_type item : collection)

     

     

     

    3. Transfer Statements:

    Transfer statements are used for transferring control in a Java program. They are:

     

    • The break statement:

     

    The break statement terminates loops ( for(;;), for(:), while, do-while) and switch statements, and it transfers control to the closest enclosing code block.

     

     

     

    while (condition) {

     

     if (condition ): {

     

    statement

     

      break;

     

     }

     

    }

     

     

    The given diagram will explain the control flow in break statements:

     

     


    • The continue statement:

     

    We use the continue statement to skip the current iteration of a loop. The diagram given here explains the control flow of the continue statement in a code block.

     

     


    • The return statement:

     

    The return statement stops the execution of a method and transfers control back to the calling code. If the parent function is void, the return statement does not carry any value. For a non-void method, the return statement will always have a return value.

     

     

    Assertions:

    In Java, assertions are used to validate the correctness of assumptions being made in the code. They are used along with boolean expressions and are mainly used for testing purposes.
     
    We use the assert keyword for assertion in Java. This feature was introduced in Java JDK 1.4 onwards. Before that, it was only an identifier. There are two ways we can use assert keyword, namely:

     

    1. assert expression;
    2. assert expression1: expression2;

       

      By default, this feature will be disabled in Java. You have to enable it by typing the following command:

       

       

       

      java -ea for all non-system classes

       

      java -ea or for particular named packages & classes alone.

       

       

      Example:

       

       

       

      public void setup() {

       

                            Connection conn = getConnection();

       

                            assert conn != null : “Connection is null”;

       

                            }

       

       

      The above code will automatically throw an assertion error Exception in thread “main” java.lang.AssertionError: Connection is null.
       
      Using assertions we can remove if & throw statements with a single assert statement.

       

       

      End note:

      In this blog, we looked briefly at Flow control statements and its syntax and when to use them while coding. We also learned about assertions in Java.

       

       

      Get one step closer to your dream job!

       

      Prepare for your Java programming interview with Core Java Questions You’ll Most Likely Be Asked. This book has a whopping 290 technical interview questions on Java Collections: List, Queues, Stacks, and Declarations and access control in Java, Exceptional Handling, Wrapper class, Java Operators, Java 8 and Java 9, etc. and 77 behavioral interview questions crafted by industry experts and interviewers from various interview panels.
       
      We’ve updated our blogs to reflect the latest changes in Java technologies.
      This blog was previously uploaded on March 25th, 2020, and has been updated on January 15th, 2022.