Loops in Java | Types, Example Program

Loops in Java are the processes that execute a block of statements repeatedly until a termination condition is met. In other words, loops are a fundamental programming construct in which a part of the program is repeated over and over until a specific goal is reached.

In Java or any other programming language, we use loops to execute the same block of statements repeatedly. Each execution of the loop is called iteration in Java.

We can execute the block of statements any number of times, from zero to infinite number, depending on the requirement. Let’s understand loops with the help of an example.

Suppose that we need to display the string “Hello world” a hundred times. It would be a tedious and boring task to have to write the following statement a hundred times:

// Writing the same statement 100 times like this will be a tedious and boring task.
   System.out.println("Hello world");
   System.out.println("Hello world");
   . . .
   . . . 
   System.out.println("Hello world");

So, how will you resolve this problem?

Java programming language provides a powerful feature called loop that controls how many times an operation or a sequence of statements has to be executed in succession.

Using a loop statement in Java program, we can simply tell the computer to display a string a hundred times without writing the code a hundred times to print the same statement, as follows:

int count = 0;
while (count < 100) 
{
  System.out.println("Welcome to Java!");
  count++;
}

The variable count is initially 0. The loop checks whether count < 100 is true. If so, it executes the body of loop to print the message “Hello world” and increments count by 1.

It repeatedly executes body of the loop until count < 100 becomes false. When count < 100 is false (i.e. when count reaches 100), the loop terminates and the next statement after the loop statement will execute.

Loop Control Structure in Java


A block of statements is executed sequentially in the loop until some conditions for the termination of the loop are met. Therefore, a loop in a program consists of two parts:

  • Control statement
  • Body of the loop

[adinserter block=”5″]
The function of control statement is to test certain conditions and then perform the repeated execution of statements contained in the body of loop.

A control structure can be classified into two types depending on the position of control statement in the loop. They are as follows:

  • Entry-controlled loop
  • Exit-controlled loop

The flowchart is shown in the following diagram.

Flow chart diagram of entry control and exit control loops in Java

Entry-controlled loop: In the entry-controlled loop, the control conditions are evaluated before the execution of body of the loop. If the specified conditions are satisfied, then the body of loop will be executed. If not satisfied, then the body of loop will not be executed. For example, while loop and for loop are entry-controlled loops.

Exit-controlled loop: In an exit-controlled loop, the specified conditions are tested at the end of the body of loop. Therefore, the body of loop is executed unconditionally for the first time. For example, the do-while loop is an exit-controlled loop.
[adinserter block=”2″]
The test conditions must be carefully declared to perform the execution of the desired number of loops in Java program.

Steps to Process Loops in Java


There are four steps to process loops in Java that are as follows:

  • Setting and initialization of a counter.
  • Execution of statements in the body of loop.
  • Evaluate for a specified condition for the execution of loop.
  • Incrementing the counter.

Types of Loops in Java


There are generally three types of loops in Java that are as follows:

  1. Simple loops
  2. Nested loops
  3. Infinite loops

We have already discussed simple loops in the above sections. Now we will discuss nested loops in Java.

Nested Loops in Java


Like conditional statements, a loop structure can be nested one inside the other. Loops placed inside another loop are called nested loops in Java. Nested loops allow us to loop over two variables.

The outside loop is called outer loop, and the inside loop is called inner loop. Each time the outer loop iterates, the inner loop iterates until its condition is satisfied. Let’s understand a simple example program that uses a pair of nested for loops.

Example 1:

public class Test {
public static void main(String[] args) 
{ 
 for(int x = 1; x <= 10; x++) { 
   for(int y = 1; y <= 10; y++) { 
      System.out.printf( "%4d", x * y); 
   } 
  System.out.println(); 
  }
 }
}

Here, x and y are called loop variables because they control the execution of a loop. In this example, there are two for loops.

The first loop that uses x as its counter variable is called outer loop. The second loop that uses y as its counter variable is called inner loop. Each loop will execute its corresponding statements 10 times. The outer loop will execute 1 to 10 only once.

But for each execution of the outer loop, the inner loop iterates 10 times and will display the multiplication of x and y for each value of x and y through the inner loop.

When the inner loop ends, a call to System.out.println() with no parameters begins a new line. Then the outer loop starts the next cycle. When the above code will be executed, it will display the following output on the console.

Output:
         1   2   3   4   5   6   7   8   9  10
         2   4   6   8  10  12  14  16  18  20
         3   6   9  12  15  18  21  24  27  30
         4   8  12  16  20  24  28  32  36  40
         5  10  15  20  25  30  35  40  45  50
         6  12  18  24  30  36  42  48  54  60
         7  14  21  28  35  42  49  56  63  70
         8  16  24  32  40  48  56  64  72  80
         9  18  27  36  45  54  63  72  81  90
         10  20  30  40  50  60  70  80  90 100

Infinite Loops in Java


If a loop repeats forever, it is called infinite loops in Java. It is also known as endless loops because the specified condition always becomes true and the body of loop is executed repeatedly, without end. For example:

int n = 1;
while(n > 0) 
{
    System.out.println(n);
  // n never changes.
}

In this example, digit 1 will be displayed an infinite number of times on the console, or at least until you terminate the program. This is because the conditions will never become false. Syntax errors are a common cause of infinite loops in a program. For example:

while(condition); // Semicolon causes infinite loop if the condition is true.

This is a common syntax error, so you must avoid putting a semicolon after the condition of while loop. If you try to do this, you will create an empty loop body and could produce an infinite loop.

Types of Loop (Iteration) Statements in Java


Java language provides three types of loop statements for performing loop operations. They are:

  1. while loop
  2. do-while loop
  3. for loop

We will learn the features and applications of each of these loop statements in the further tutorials one by one.

When to Use Loops in Java Programming?


Loops can be useful in those scenarios where we need to repeat a task multiple times or iterate over a collection of data elements. Although, it is necessary to select the correct type of loop based on the specific requirements of your application or program.

There are the following some common scenarios where you should think about using loops in your Java programs.

(a) When you have a dataset that needs processing or manipulation, loops can be helpful for you to iterate over the data.

(b) Loops are convenient when you search for specific elements in an array or a list. You can iterate over the collection by conditional statements to filter out the elements that meet certain criteria.

(c) If you want to find the sum, average, or any other aggregation of a set of numbers, use loops to calculate sum, or average.

(d) Loops are useful when you want to display each element of data sequentially in tabular or list form.

(e) Loops can be useful to produce numerical sequences, such as the Fibonacci series, prime numbers, or any other sequence that follows a specific pattern or logic.

(f) You can use loops to validate the input until it meets the required conditions, ensuring that you get the correct and expected values.

(g) We often use loops when working with data structures like arrays, lists, and elements to access, or modify each element in the data structure.

Best Practices for Using Loops


To write clean and maintainable program code in Java using loops, consider the following best practices:

  • Use meaningful variable names for loop control.
  • Comment your code for better readability.
  • Prefer the for loop when the number of iterations is known.
  • Prefer the while loop when the number of iterations is unknown.

⇐ PrevNext ⇒