Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Infinite Loop Example in Java

Last Updated on January 31, 2023 by Prepbytes

In this article, we will discuss the Infinite loop concept, and how the infinite loop can be implemented using loops such as for loop, while loop, and do-while loop.

What is Infinite Loop in Java?

An infinite loop in java is a sequence of instructions that loops indefinitely until the system crashes. In Java, an infinite loop occurs when the loop’s ending condition is not met. An endless loop in Java is usually a programming error, but it can sometimes be used intentionally, such as in a wait condition.

All loops, including while, for, and do-while loops, have one feature: the condition. Loops are conducted until the condition is satisfied. In this article, we will look at the case where the condition always evaluates to true, i.e. it never fails.

This will result in an indefinite loop that will continue to run until the application is terminated or the system crashes.

In most circumstances, infinite loops are produced as a result of a programming error, but in certain cases, infinite loops are purposely made in order for some code to run on a regular basis.

These loops are only halted when the application is terminated or the system fails.

Flow Chart of Infinite Loop

Elaboration:

  • First, we check our loop’s entering condition.
  • If the condition is true then we enter the loop or else we end the loop.
  • Inside the loop, we start executing statements present there.
  • Due to some bug or maybe intentionally, our loop’s condition always remains true. Because of this effect, our loop runs to infinity.
  • This endless loop will only stop either when the application terminates or the system crashes.

Reasons for Infinite Loop Occurrence

Reason 1: Infinite loop with condition that is always true
we know that the condition in the loop statement has to always evaluate to true for it to become an infinite Loop.

We can specify a condition that is always true. For instance, the conditions 1 == 1 and 0 == 0 are always true. The condition is always true no matter how many times the loop runs, and the loop will run indefinitely.

Code Implementation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // implementation starts from here
        
        while(1==1){
            System.out.println("PrepBytes");
        }
        
    }
}

Output:

PrepBytes
PrepBytes
PrepBytes
PrepBytes
PrepBytes
         .
         .
         .
         .

Reason 2: Infinite loop with no update to variables participating in the condition
These infinite loops might occur if we fail to update the variables involved in the condition.

In the following example, variable i has been set to 5, one would typically decrease i to display prepBytes 5 times. However, if the decrease instruction in the loop update portion is omitted, i is never updated. As a result, the loop becomes endless.

Code Implementation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // code implementation starts from here
        
        for(int i=5;i>0;){
            System.out.println("PrepBytes");
        }
        
    }
}

Output:

PrepBytes
PrepBytes
PrepBytes
PrepBytes
PrepBytes
         .
         .
         .
         .

Implementation of Infinite Loops in Java

Now, let’s try to implement an infinite loop in Java.

Using For Loop

A For loop is a control flow statement in programming that allows you to iterate over a range of values. The for loop has the following basic syntax:

Syntax of For Loop

for(initialization; condition expression; updation)

In case of for loop the initialization expression, condition expression, and updation are optional whereas, in the case of the while loop, the condition expression is mandatory. So if we leave this expression empty, the for loop will execute for an indefinite time.

Code Implementation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // code goes here
        
        for(;;){
            System.out.println("Prep Bytes");
        }
        
    }
}

Output:

Prep Bytes
Prep Bytes
Prep Bytes
         .
         .
         .
         .
         .

Explanation:
In the code above, the body of the loop is executed till the condition expires.

However, as we discussed above, condition expression in For loop is optional and we can leave it empty.

Since there is no condition present to evaluate to true, For loop runs for infinite time.

Using While Loop

A while loop is a control flow statement in programming that allows you to repeatedly execute a block of code as long as a certain condition is true. The while loop has the following basic syntax:

Syntax of While Loop

while(condition){
  // code inside while loop
}

If the condition is true, the code within the body of the while loop is performed; otherwise, the while loop is ended. So we must give a condition that always evaluates to true, which can be accomplished by passing true or 1==1 or 0==0 as the condition in the while loop.

Code Implementation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        while(true){
            System.out.println("Hello World");
        }
        
    }
}

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
        .
        .
        .
        .

Using Do-while Loop

A do-while loop is a control flow statement in programming that allows you to repeatedly execute a block of code, and then check a condition to determine if the loop should continue or terminate. The do-while loop has the following basic syntax:

Syntax of the do-while loop

do{
   // code inside the do-while loop
}while(condition);

The do-while loop in Java is similar to the while loop in Java, with one slight difference. The do-while loop runs the loops do block and then checks the condition. As a result, even if the condition is false, the do-while loop is completed at least once.
The condition expression, like the while loop, is required.
We will pass true as the condition, as we did in the while loop, and the above loop will execute indefinitely.

Code Implementation:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        do{
            System.out.println("Ritik Sharma");
        }while(true);
    }
}

Output:

Ritik Sharma
Ritik Sharma
Ritik Sharma
Ritik Sharma
     .
     .
     .
     .
     .

Summary

  • In Java, an endless loop is a sequence of instructions that loops indefinitely until the program or the system is terminated.
  • In the case of a while loop, we can pass true as the condition to execute the while loop indefinitely, in the case of a for loop, we can leave the expression empty to perform the for loop indefinitely, and in the case of a do-while loop, we can pass true as the condition to execute the do-while loop indefinitely.
  • In most cases, infinite loops in Java are considered a programming fault; nevertheless, they can be purposeful.
  • If a program’s execution time is exceeded, the TimeLimitExceeded (TLE) error is thrown.

Leave a Reply

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