Java Loops - What are loops in Java

During program execution, there are situations where code blocks need to be executed multiple times. Normally, statements are executed sequentially: the first statement in a function is executed first, then the second statement, and so on.

Programming languages ​​provide various control structures that allow for more complex execution paths.

A loop statement is used to execute a statement or a group of statements multiple times, following is the general form of a loop statement in most programming languages ​​−

Cycle Flowchart

 

The Java programming language provides the following types of loops to handle looping requirements, which can be learned by clicking on each of the links below.

serial number cycle describe
1 while loop Repeats a statement or group of statements while a given condition is true, it tests the condition before executing the loop body.
2 for loop Executes a series of statements multiple times and abbreviates the code that manages loop variables.
3 do...while loop Like while statement, but it tests the condition of the loop body at the end.

 

1. Loop control statement

Loop control statements alter execution from the normal execution order. When execution leaves a scope, all automatic objects created in that scope are destroyed.

Java supports the following control statements which can be understood and learned by clicking on each link below.

serial number control statement describe
1 break statement Terminates a loop or switch statement and immediately transfers execution to switch the statement on or after the loop.
2 continue statement Causes the loop to skip the rest of its body and immediately retests its state before repeating.

 

2. Enhance Java loop

Starting with Java 5, enhanced forloops were introduced. This is primarily useful for traversing collections of elements, including arrays.

Syntax
Following is the syntax of boost forloop −

for(declaration : expression) {
   // Statements
}

In the syntax above,

  • declaration- The newly declared block variable is of a type compatible with the array element to be accessed. The variable will be available in the for block and its value will be the same as the current array element.
  • expression- This is the array to loop through. expression( expression) can be a returned array variable or a method call.

example

public class Test {

   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};

      for(int x : numbers ) {
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names = {"James", "Curry", "Kobe", "Jordan"};

      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

Executing the above sample code yields the following result −

10, 20, 30, 40, 50,
James, Curry, Kobe, Jordan,

1. While Loop

The while loop in Java works similar to that in Python. It allows us to execute a block of code several times as long as the condition evaluates to true.

There is only a syntactical difference when compared to Python. In Python, the block of code is separated by indentation, whereas in Java the curly braces {} are used.

Syntax

while (condition) {

    // body of loop

}

 

The following code snippet prints the next three consecutive numbers after a given number.

Example

class Main {

    public static void main(String[] args) {

        int num = 4;

        int counter = 0;

 

        while (counter < 3) {

            num = num + 1;

            System.out.println(num);

            counter = counter + 1;

        }

    }

}

 

Output

5

6

7

 

1.1 Possible Mistakes

Let's take a look at some of the most common mistakes that happen when using loops.

1.1.1 Incorrect Termination Condition

Wrong Code

class Main {

    public static void main(String[] args) {

        int num = 4;

        int counter = 0;

        boolean condition = (counter < 3);

 

        while (condition) {

            num = num + 1;

            System.out.println(num);

            counter = counter + 1;

        }

    }

}

 

Output

Time Limit Exceeded

The above code runs into an infinite loop. The while block will keep executing as the value in the condition variable is always true

 

1.1.2 Not Updating Counter Variable

Wrong Code

class Main {

    public static void main(String[] args) {

        int n = 4;

        int counter = 0;

 

        while (counter < 3) {

            n = n + 1;

            System.out.println(n);

        }

    }

}

 

Output

Time Limit Exceeded

In the above code, we are not updating the counter variable inside the while loop. Since the counter value does not change, the condition will always evaluate to be true, resulting in an infinite loop.

 

2. Do-While Loop

The do...while loop is similar to the while loop. The only difference is that in the while loop the condition check is made initially, whereas in the do...while loop the check is made after the do...while block of code has been executed.

Syntax

do {

    // body of loop

} while(condition);

 

 

Now, let's write the code to print the next three numbers from a given number using do...while loop.

Example

class Main {

    public static void main(String[] args) {

        int n = 4;

        int counter = 0;

 

        do {

            n = n + 1;

            System.out.println(n);

            counter = counter + 1;

        } while (counter < 3);

    }

}

 

Output

5

6

7

The do-while loop is executed at least once regardless of the condition.

The following code snippet prints the output for once even though the condition is false

Example

class Main {

    public static void main(String[] args) {

        int n = 3;

        boolean condition = (n > 10);

 

        do {

           System.out.println("Number is greater than 10");

        } while (condition);

    }

}

 

Output

Number is greater than 10

Note: Python does not have an equivalent syntax for do-while loop

 

3. For Loop

Java for loop is used to execute a block of code a certain number of times. It is generally used where the number of iterations is known.

Syntax

for (initialExpression; condition; increment/decrement) {

    // body of the loop

}

 

  1. initialExpression: Here, the variables are defined or initialized. initialExpression is executed only once.

  2. condition: It is evaluated for every iteration of the loop. If the condition evaluates to true, the body of the for loop is executed.

  3. increment/decrement: Here, the initialExpression is updated. It is executed at the end of every iteration of the for loop.

  4. The condition is evaluated again. This process continues until the condition evaluates to false

The below for loop iterates three times and prints the next three numbers after the given number.

Example

class Main {

    public static void main(String[] args) {

        int num = 4;

 

        for (int counter = 0; counter < 3; counter = counter + 1 ) {

            num = num + 1;

            System.out.println(num);

        }

    }

}

 

Output

5

6

7

 

3.1 Possible Mistakes

Wrong Loop Syntax

Leaving out the semi-colons in a for loop or replacing them with any other special characters such as commas (,) will result in an error.

Wrong Code

class Main {

    public static void main(String[] args) {

        int num = 4;

 

        for (int counter = 0, counter < 3; counter = counter + 1 ) {

            num = num + 1;

            System.out.println(num);

        }

    }

}

 

Output

file.java:5: error: ';' expected

   for (int counter = 0, counter < 3 ; counter = counter + 1 ) {

                            ^

file.java:5: error: illegal start of type

   for (int counter = 0, counter < 3 ; counter = counter + 1 ) {

                              ^

file.java:5: error: ')' expected

   for (int counter = 0, counter < 3 ; counter = counter + 1 ) {

                               ^

file.java:5: error: ';' expected

 

Enhanced for loop in Java

Enhanced loops are used to traverse collection of elements like Collection classes like List, Map, and Arrays also

Syntax

for(declaration : expression) {
   // Statements
}

 

  • Declaration − The newly declared block variable, is of a type compatible with the elements of the array we are accessing. The variable will be available within the for block and its value would be the same as the current collection/array element.

  • Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array

 

Example code for Enhanced loop

public class LoopTest {

   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};

      for(int x : numbers ) {
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] loops = {"Loop", "While Loop", "Do While Loop", "For Loop"};

      for( String loop : loops ) {
         System.out.print( loop );
         System.out.print(",");
      }
   }
}

 

Conclusion

  • In for and while loops, the condition is checked before the execution of the corresponding block of code.

  • In do...while loop, the condition is checked after the execution of the corresponding block of code. The do...while loop is executed at least once