Loops in Java with Syntax and Examples

In Java, to get certain specific kinds of results or to find something in a huge collection of data, we use loops. They help you to perform a certain set of statements repetitively and hence reach your desired result. In this blog you will learn what loops in Java are, how they work, what are the different types of loops, how are these types different from each other and what to take care of while working with loops.

What are loops in Java?

Loops in java are certain statements or commands which help the programmer to iterate over a set of statements. It repetitively executes a set of statements based on a condition. If the condition is true then the machine executes the set of statements given inside the loop body. If the condition is false then the machine terminates the loop, that is, it skips the set of given statements and executes the next part of the program instead.

  • We use loops in Java to repeat the execution of a particular block of statements.
  • The machine checks the condition before entering into the loop. If the condition is true only then the machine executes the statements inside the loop, otherwise it skips them.
  • There are different looping statements such as for,while and do-while in Java.
  • When there is another loop inside a loop we address it as a nested loop.
  • We address a loop as entry control if in it the machine checks the condition at the beginning of the iteration.We address a loop as exit control loop if in it the machine checks the condition at the end of each iteration.

Java for() loop

For loop is the most popular looping statement in Java. This has a format which is:

for(initialization;condition;updation). Each part is explained below:

Initialization: So, here we give an initial value to the variable which we are using to loop through a specific set of statements.

Condition: This is a specific condition that the machine checks at the start of the loop, that is,before entering the loop and after each iteration. Only if this condition is true, the machine executes the statements inside the loop.

Updation: At the end of each iteration and before the beginning of the new one, the machine updates the value of the variable which we are using for the loop.

After this, there is a set of statements inside the loop which we refer to as the body of the loop. These statements are enclosed within curly braces.

Java for() loop Example:

//FirstCode Example to illustrate for loop in Java
class FirstCode
 { public static void main(String[] args)
  { int i=0;
   System.out.println(“Program to print the table of 2”);
   for(i=1;i<=10;i++)
     {
      System.out.println(i*2);
                              }
                               }
                                }

Output:

Program to print the table of 2
2
4
6
8
10
12
14
16
18
20

for() loop is an entry control loop because in this looping statement the machine always checks the condition before the beginning of each iteration.

The given image shows the working of java for() loop.

java for loop

Java Enhanced for() loop

This is a newer version of for() loop which is a read only version. This version was introduced in Java 5. It allows a programmer to loop through a structured collection or set of values without changing the data or modifying the data present there. This can be used when we are working with arrays. This is also known as for each: loop.

Format: for(<data type> <variable>: <array/collection of objects>)

For Example:

//FirstCode program to illustrate for:each loop in java
class FirstCode
{
 public static void main(String[] args)
 {
  int arr[]={2,3,4,6,8};
  for( int i:arr)
  {
   System.out.println(i);
    }
     }
       }

Output:

2
3
4
6
8

Java while() loop

This is a looping statement in which the machine checks the condition while starting the loop. The variable which we will use to loop has to be initialized outside the loop, before beginning it. We will perform the updation at the end of the block which contains the body of the loop. It is an entry control loop.

Format:

initialization;

while(<condition>)

{

set of statements;

updation;

}

//FirstCode Program to illustrate java while loop
class FirstCode
{
 public static void main(String[] args)
  {
    Int i,j;
    i=0
    while(i<11)
    {
     System.out.println(i);
     i++; }
           }
             }

Output:

1
2
3
4
5
6
7
8
9
10

The given image shows the working of java while() loop.

java while loop

Java do while() loop

Other than the fact that this is an exit control loop, this is similar to the while loop. In this, the condition is checked at the end of the loop. This means even if the condition is not satisfied the statements inside the loop are executed at least once.

Format:

initialization

do

{

Statements to be executed;

updation;

}

while(<condition>)

//FirstCode Program to illustrate do while loop in java
class FirstCode
{
  public static void main(String[] args)
  {
    Int i,j;
    i=0
    do
    {
      System.out.println(i);
      i++; }
      while(i<11)
               }
                }

The given image shows the working of java do{} while() loop.

java do while loop

Things to take care of while working with loops in java

1. Sometimes, because of the wrong kind of updation part the loop can keep running infinitely. This happens because the condition which is checked before beginning the next iteration keeps getting satisfied. As the result of checking the condition is true the loop keeps getting executed infinitely.

For Example;

//FirstCode Example to illustrate looping errors in java
class FirstCode
 { public static void main(String[] args)
  { int i=0;
  ;
    for(i=1;i<=2;i=i-1)
     {
      System.out.println(i);
                           }
                            }
                             }

2. While working with arrays or any other kind of set of objects, we keep adding new data elements to it and sometimes we exceed the memory limit.

For Example:

//FirstCode Example to illustrate looping errors in java
class FirstCode
{ public static void main(String[] args)
 { int i=0;
 int arr[]= new int[5];
 for(i=0;i<=5,i++)
    {
     a[i]=i+1;
              }
               }
                }

Comparison of java for(), while() and do while()

for() while() do while()
It has a compact format where we give initialization, updation and condition all three together. In this, we do the initialization outside the loop, updation at the end of the statements and the machine checks the condition at the beginning. In this, initialization has to be done outside the loop, updation at the end of the statements and condition is also checked at the end of each iteration.
It is an entry control loop. This is an entry control loop. It is an exit control loop

Summary

To become a great Java programmer we need to know how to work with the looping statements. Hence, in this blog we learned what loops in Java are, what is the format to work with them, how they work, what are their types and the comparison of different loops that is how they are different or similar to each other. We also got to know what we should keep in mind while working with the loops.

Leave a Reply

Your email address will not be published. Required fields are marked *