Loops in Java (for, while, do-while) – Faster Your Coding with Easy Method

Whenever I hear about loops, homework from school days strikes my mind. Honestly, I made many mistakes in English and my teacher used to give me punishment to write down those incorrect spellings and sentences for at least 10-15 times. The concept of Loops in Java is exactly similar to my homework.

Loops in Java are designed to perform a specific task repeatedly. There are many types of loops available in Java to perform a task. Here, we will discuss do-while, while, for loops with their syntaxes and examples. A beginner must know the concept of loops. This is the fundamental concept of programming.

What are Loops in Java

Java is Multi-featured language, loops are a way to run a particular instruction or function a number of times. Loops are basically used to perform a particular task repeatedly. Any kind of iteration in programming is done with the help of loops.

Java has 3 ways of executing the loops, they are all nearly similar, with some syntax and condition checking differences.

Types of Java Loops

Types of Loops in Java

1. While loop in Java

In Java, while loop is continuously executed if the Boolean condition becomes true, it can be considered as a repeating if statement. While loop first checks the body of the loop then it will be executed.

Before we start the syntax, you must know Basic Java Syntax

The syntax of Java While Loop-

while (boolean condition)
{
   loop statements...
}

While loop is an entry controlled loop, i.e. the condition is tested before the loop.

The condition is tested and the iteration follows until the condition becomes false, and that marks the end of the loop.

While-Loop-in-Java

Example-

package JavaLoops;

public class WhileLoopDemo 
  {
    public static void main(String args[])
    {
           int count = 1;
           // Exits when count becomes greater than 5
           while (count <= 5)
             {
               System.out.println("Value of count is:" + count);
               //increment the value of count for next iteration
               count++;
              }
       }
    }

Output-

while Loop

2. For loop in Java

Java for loop is a concise version of while loop, it provides the user to write the whole condition, i.e. initialization, condition and Increment/decrement in one line.

Syntax of Java for loop

 for (initialization condition; testing condition; increment/decrement)
{
    statement(s)
}

A for loop in java is also an entry controlled loop, we first initialize the variables in use and then the condition is tested, and accordingly, increment or decrement takes place.

For-loop-Java

Example- 

// Java program to illustrate for loop

public class ForLoopDemo {
  public static void main(String args[])
    {
          
           // Exits when count becomes greater than 5
           for(int count=1;count<=5;count++)
        	 //initialization; condition; increment/decrement
             {
               System.out.println("Value of count is:" + count);
               //increment the value of count for next iteration
              }
       }
}

Output-

For Loop

Enhanced for loop

This version was introduced in Java 5, this feature allows you to iterate with elements of arrays. This feature should only be used when the index is unknown.

Syntax –

Join DataFlair on Telegram
for (T element:Collection obj/array)
{
    statement(s)
}

Example of enhanced for loop in Java

// Java program to illustrate enhanced for loop
package JavaLoops;

public class EnhancedForLoop 
{
  public static void main(String args[])
    {
    String array[]= {"Java","Hadoop","Big Data","Machine Learning","Artificial Intelligence","Python"};
    //enhanced for loop
    for(String count:array)
    {
    	System.out.println("DataFlair provides training on "+count+" course");
    }
  }
}

Output-

Enhanced For Loop

3. do while loop in Java

A do while statement is an exit controlled loop, i.e. it checks the condition after the execution of the loop. It means that the body of the loop is executed once if the condition is true or false.

Syntax of Java do-while loop-

do
{
    statements..
}
while (condition);

Recommended Reading – Decision Making in Java

Example of do while loop  in Java

package JavaLoops;
public class DoWhileLoopDemo 
  {
   public static void main(String args[])
      {
         int count = 21;
         do 
           {
            //The line while be printer even
            //if the condition is false
              System.out.println("Value of count is:" + count);
              count++;
           }
          while(count<20);
    }
}

Output-

Do While Loop

A Best & Interactive Way to Learn Java Quickly – Java Infographic

Pitfalls in Loops in Java

1. Infinite loop

This loop takes place when the condition for some reason fails.

Example-

//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
    public static void main(String[] args)
    {
        // infinite loop because condition is not apt
        // condition should have been count>0.
        for (int count = 5; count!= 0; count -= 2)
       {
            System.out.println(count);
        }
        int count = 5;
        // infinite loop because update statement
        // is not provided.
        while (count == 5)
        {
            System.out.println("fail");
        }
   }
}

2. Shortage of memory

This happens when there is a continuous addition in the loop but there occurs a shortage of memory.

Example 

//Java program for out of memory exception

package JavaLoops;

import java.util.ArrayList;
public class ShortageOfMemoryInLoop {
  public static void main(String args[])
  {
    ArrayList<Integer> ar=new ArrayList<>();
    for(int count=0;count<Integer.MAX_VALUE;count++)
    {
      ar.add(count);
    }
  }
}

Output- 

Out of Memory

Java Quiz

Summary

Loops (for, do-while and while) in Java helps a programmer to save plenty of his time. Repetition causes unwillingness to work. So, loops help you to do your work interactively and swiftly.

I wish, I knew this concept during my school days and it would’ve helped me to complete my homework within seconds. Life would’ve been much easier😅.

Learn Access Modifiers in Java with Example.

Hope, you like the explanation. Please share your experience with Loops in Java.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.