Java Loops – A Complete Guide for Beginners!

Have you ever forgot to do your homework and as a punishment you were asked to write “I will do my homework on time.” for at least 40-50 times? It was boring as well as time-consuming, right? Well, Java Loops works exactly the same.

Loops in programming allow a set of instructions to be executed repeatedly until a certain condition is fulfilled. Loops are also known as iterating statements or looping statements. In this article, we will learn about the various loops in Java.

Need for Loops in Java

While programming, sometimes, there occurs a situation when we need to execute a block of code several numbers of times. In general, these statements execute in a sequential manner: The first statement in a function executes first, followed by the second, and so on.

But this makes the process very complicated as well as lengthy and therefore time-consuming. Therefore, programming languages provide various control structures that allow for such complex execution statements.

Before moving towards the types of loops, we will first discuss the general syntax of a loop with the help of elements that control a loop.

Java Loops

In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true.

This particular condition is generally known as loop control. For all three loop statements, a true condition is the one that returns a boolean true value and the false condition is the one that returns the boolean false value.

Elements in a Java Loop

Every loop has its elements or variables that govern its execution. Generally, a loop has four elements that have different purposes which are:

  • Initialization Expression(s)
  • Test Expression(Condition)
  • Update Expression(s)
  • Body of the loop

We will discuss each of the above elements for a better understanding of the working of the loops.

1. Initialization Expression(s)

Before entering into a loop, we must initialize its control variable. The initialization of the control variable takes place under initialization expression. It initializes the loop variable(s) with their first value. The initialization expression gets executed only once at the beginning of the loop.

2. Test Expression

The test expression is an expression whose truth (boolean) value decides whether the loop body will be executed or not. The execution or termination of the loop depends on the test expression which is also called the exit condition or test condition.

If the test expression evaluates to true that is, 1, the loop body is executed, otherwise, the loop is terminated.

In an entry-controlled loop, the test expression is evaluated before entering into a loop whereas, in the exit-controlled loop, the test expression is evaluated before exiting from the loop. In Java, the for loop and while loop are entry-controlled loops, and do-while loop is an exit-controlled loop.

3. Update Expression(s)

The update expression(s) changes the values of the loop variables. The update expression is executed at the end of the loop after the loop body gets executed. For example, an update expression may be increment or decrement statements.

4. The Body of the Loop

The statements which execute repeatedly (as long as the test expression is non zero) form the body of the loop. The code inside the loop body will be executed or not, depends on the value of the test expression.

If the value evaluates to be true then the loop body gets repeatedly executed, otherwise, it gets terminated.

Following diagram explains an Iteration or a loop construct:

loop constructor

Types of Loops in Java

1. The for Loop

The for loop in Java is an entry controlled loop that allows a user to execute a block of a statement(s) repeatedly with a fixed number of times on the basis of the test expression or test-condition. This is the easiest to understand Java loops.

All its loop-control elements are gathered at one place, on the top of the loop within the round brackets(), while in the other loop constructions of Java, the loop elements are scattered about the program.

The syntax or general form of for loop is:

for(initialization expression(s) ; test-expression ; update-expression(s))
{
     body of the loop ;
}

For Example:

int x = 0;
for( x = 1 ; x <= 10 ; x++ )
{
  System.out.println(Value of x: “ +x);
}

Code Snippet to illustrate the use of for statement/loop:

package com.TechVidvan.loopsDemo;
public class ForLoopDemo
{
  public static void main(String args[])
  {
    int i;
    for(i = 10; i >= 1; i--)
    {
      System.out.println("The value of i is: "+i);
    }
  }
}

Output:

The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
The value of i is: 1

The following figure outlines the working of a for loop:

 

for loop in Java

Now that you are familiar with the working of a for loop, let us take another example where there are multiple statements in the loop body:

Code:

package com.TechVidvan.loopsDemo;

public class ForLoopDemo
{
  public static void main(String args[])
  {
    int i,sum;
    for(i = 1 , sum = 0; i <= 10; ++i)
    {
      System.out.println("The value of i is: "+i) ;
      sum = sum + i;
    }
    System.out.println("The sum of first 10 numbers is: " +sum) ;
  }
}

Output:

The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
The value of i is: 6
The value of i is: 7
The value of i is: 8
The value of i is: 9
The value of i is: 10
The sum of first 10 numbers is: 55

In the above program, there are 2 initialization expressions: i = 1 and sum = 0 separated by comma. The initialization part may contain as many expressions but these should be separated by commas. The initialization part must be followed by a semicolon(;). Both the variables i and sum get their first values 1 and 0 respectively.

Tip: Use for loop when you have to repeat a block of statements a specific number of times.

The for loop Variations

Java offers several variations in the loop that increases the flexibility and applicability of for loop. The different variations of for loop are discussed below:

1.1. Multiple Initializations and Update Expressions

A for loop may contain multiple initializations and/or update expressions. These multiple expressions must be separated by commas. We have already seen an example of multiple initialization expressions in the previous program.

The for loop of that program can be alternatively written as follows:

for( i = 1, sum = 0 ; i <= 10 ; sum +=i, ++i )
System.out.println(i);

The above code contains two initialization expressions i = 1 and sum = 0 and two update expressions sum += i and ++i. These multiple expressions are executed in sequence.

Tip: The comma operator in a for loop is essential whenever we need more than one index.

1.2. Optional Expressions

In a for loop, initialization expressions, test expressions and, update expressions are optional that is, you can skip any or all of these expressions.

Say, for example, you have already initialized the loop variables and you want to scrape off the initialization expression then you can write for loop as follows:

for( ; test-expression ; update-expression(s))
loop-body

See, even if you skip the initialization expression, the semicolon (;) must be following it.

Following code fragment illustrates the above concept:

package com.TechVidvan.loopsDemo;

public class ForLoopDemo
{
  public static void main(String args[])
  {
    int i = 1, sum = 0 ;
    for( ; i <= 10 ; sum +=i, ++i )
      System.out.println(i);
    System.out.println("The sum of first 10 numbers is: " +sum) ;
  }
}

Output:

1
2
3
4
5
6
7
8
9
10
The sum of first 10 numbers is: 55

Similarly, we can also skip or omit the test expressions and update expressions.

For example,

for( j = 0 ; j != 224 ; )
j += 11 ;

If the variable j has already been initialized, then we can write the above loop as,

for( ; j != 224 ; )
j += 11;

Tip: The loop-control expressions in a for loop statement are optional, but semicolons must be written.

1.3. Infinite Loop

An infinite loop can be created by skipping the test-expression as shown below:

package com.TechVidvan.loopsDemo;
public class ForLoopDemo
{
  public static void main(String args[])
  {
    int x;
    for( x = 25 ; ; x-- )
      System.out.println(“This is an infinite loop”);
  }
}

Output:

This is an infinite loop…

Similarly, we can also skip all three expressions to create an infinite loop:

for( ; ; ; )
loop body

1.4. Empty Loop

When there is no statement in the loop-body of the loop, then it is called an empty loop. In such cases, a Java loop contains an empty statement that is, a null statement. Following for loop is an example of an empty loop:

for( j = 20 ; j >=0 ; j– ) ; //See,the loop body contains a null statement

An empty for loop has its applications in the time delay loop where you need to increment or decrement the value of some variable without doing anything else, just for introducing some delay.

1.5. Declaration of variables inside loops

When we declare any variable inside for loop, we can not access the variable after the loop statement is over. The reason is that as the variable is declared within a block of statement its scope becomes the body of the loop. Therefore, we can’t access it outside the loop body.

Following code explains this concept:

package com.TechVidvan.loopsDemo;
public class ForLoopDemo
{
  public static void main(String args[])
  {
    for(int x = 25 ; x>=0; x -= 5)
    {
      System.out.println("Inside the loop");
    }
    System.out.println(x); //Accessing x after the loop body gives an error
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
x cannot be resolved to a variable
at project1/com.TechVidvan.loopsDemo.ForLoopDemo.main(ForLoopDemo.java:11)

In the above program, the statement System.out.println(x); is invalid as the scope of x is over. A variable is not accessible outside its scope, that’s why there is an error.

2. The while Loop

The next loop available in Java is the while loop. The while loop is an entry-controlled loop.

The syntax or general form of while loop is:

while(test-expression)
loop-body

In a while loop, the loop-body may contain a single, compound or an empty statement. The loop repeats while the test expression or condition evaluates to true. When the expression becomes false, the program control passes to the line just after the end of the loop-body code.

In a while loop, a loop variable must be initialized before the loop begins. And the loop variable should be updated inside the while loop’s body.

Following code shows the working of a while loop:

Code Snippet to illustrate while loop:

//program to calculate the factorial of a number

package com.TechVidvan.loopsDemo;
public class WhileLoopDemo
{
  public static void main(String args[])
  {
    long i = 0, fact = 1, num = 5 ;
    i = num ;
    while(num != 0)
    {
      fact = fact * num;
      --num;
    }
    System.out.println("The factorial of " + i + " is: " +fact);
  }
}

Output:

The factorial of 5 is: 120

In the above code, as long as the value of num is non-zero, the loop body gets iterated that is, the variable. Each time the value of fact gets updated when it is multiplied with num, then the next operation is the decrement in value of num.

And after that, again the test-expression (num) is executed. If it is false, the loop is terminated otherwise repeated.

The following figure outlines the working of a while loop:

while loop in Java

The while loop Variations

A while loop also has several variations. We will discuss each of these variations:

2.1. Empty while Loop

An empty while loop does not contain any statement in its body. It just contains a null statement which is denoted by a semicolon after the while statement:

:
long wait = 0;
while( ++wait < 10000)
; //null statement
:

The above code is a time delay loop. The time delay loop is useful for pausing the program for some time. For instance, if an important message flashes on the screen and before you can read it, it goes off.

So, here you can introduce a time delay loop so that you get sufficient time to read the message.

2.2. Infinite while Loop

A while loop can be an infinite loop if you skip writing the update statement inside its body. For example, the following code is an example of an infinite while loop:

package loopsDemo;
public class WhileLoopDemo
{
  public static void main(String args[])
  {
    int j = 0;
    while(j <= 10)
    {
      System.out.println( j * j);
    }
    j++;

    //writing the update expression outside the loop body makes an infinite loop
  }
}

Output:

0
0 …

The above loop is an infinite loop as the increment statement j++ is not included inside the loop’s body. The value of j remains the same (that is, 0) and the loop can never terminate.

We can also write boolean value true inside the while statement to make an infinite while loop. As condition will always be true, the loop body will get executed infinitely. It is shown below:

while(true)
System.out.println(“This is an infinite loop”);

3. The do-while Loop

Unlike the for and while loops, the do-while loop is an exit-controlled loop which means a do-while loop evaluates its test-expression or test-condition at the bottom of the loop after executing the statements in the loop-body.

This means the do-while loop always executes at least once !!

Need for do-while loop:

In the for and while loops, the condition is evaluated before executing the loop-body. The loop body never executes if the test expression evaluates to false for the first time itself.

But in some situations, we want the loop-body to execute at least once, no matter what is the initial state of the test-expression. In such cases, the do-while loop is the best option.

The syntax or general form of do-while loop is:

do
{
    statement(s);

} while(test-expression) ;

The braces { } are not necessary when the loop-body contains a single statement.

Following code shows the working of a do-while loop:

Code Snippet to illustrate the do-while loop:

//program to print all upper case letters
package com.TechVidvan.loopsDemo;
public class DoWhileLoopDemo
{
  public static void main(String args[])
  {
    char ch = 'A' ;

    do
    {
      System.out.println( ch + " " );
      ch++;
    } while(ch <= 'Z');
  }
}

Output:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The above code print characters from ‘A’ onwards until the condition ch<= ‘Z’ becomes false.

The following figure outlines the working of a do-while loop:

do-while loop in Java

The‌ ‌do-while‌ ‌loop‌ ‌is‌ most commonly used ‌in‌ ‌the‌ ‌menu‌ ‌selection‌ ‌systems,‌ ‌in which the user can see the menu at least once.‌ ‌Then‌ ‌according‌ ‌to‌ ‌the‌ ‌user’s‌ ‌response,‌ ‌it‌ ‌is‌ ‌either‌ ‌repeated‌ ‌or‌ ‌terminated.‌ ‌

Nested Loops in Java

When a loop contains another loop in its body than it is called a nested loop. But in a nested loop, the inner loop must terminate before the outer loop. The following is an example of “nested” for loop:

Code to illustrate nested for loop:

package com.TechVidvan.loopsDemo;
public class NestedLoopDemo
{
  public static void main(String args[])
  {
    int i, j;
    for( i = 1 ; i <= 5 ; ++i)
    {					//outer loop
      System.out.println();
      for( j = 1 ; j <= i ; ++j)	//inner loop
      System.out.println( "* " );
    }
  }
}

Output:

*
* *
* * *
* * * *
* * * * *

Summary

The Loops in Java helps a programmer to save time and effort. Repetition of statements causes a delay in time. So, loops help us to do the tasks in an easy and efficient manner. In this article, we discussed the three types of loops: for, while and do-while loop.

We covered them with the help of examples and code snippets so that you can understand them better. Also, we have discussed the variations and special cases in the for and while loops. We also covered the concepts of nested loops in the article.

Thank you for reading our article. I hope this article will help you to strengthen your concepts in Java loops.

Do share your feedback through the comment section below.