Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Thursday, December 10, 2020

Creating Infinite Loops In Java

1. Overview

In this tutorial, We'll learn how to create infinite loops in java. Creating infinite loops can be done in different ways using for loop, while loop and do while loops.

Every loop will have the condition and loop will be running untill the condition is satisfied that means condition is returning true value. If the condition is not becoming false then it is called as unlimited or never ending loop.

90% of infinite loops are created are errors by programmers but there are few situation where we use the infinite loops for some logics those should be running for every 15 mins or periodically. These loops will exits only on the termination of application.

Let us explore the different ways.

Creating Infinite Loops In Java


2. Using for loop


First, start with the for loop and use the boolean value true in the condition place inside for loop.

package com.javaprogramto.programs.infinite.loops;

/**
 * Example to create infinite loop with for loop.
 * 
 * @author javaprogramto.com
 *
 */
public class ForLoopInfiniteExample {

	public static void main(String[] args) {

		// for loop condition to true.
		// this loop runs forever.
		for (; true;) {
			// core logic
			System.out.println("Running loop");
		}
	}
}

3. Using while loop


Next, use the while loop with true boolean in condition.

public class WhileLoopInfiniteExample {

	public static void main(String[] args) {

		// while loop condition to true.
		// this loop runs forever.
		while (true) {
			// core logic
			System.out.println("Running while loop");
		}
	}
}

4. Using do while loop


Finally use the do while loop to create infinite loop. But, this is very rarely used in the java and first while block will be executed then condition is checked. 


/**
 * Example to create infinite loop with do-while loop.
 * 
 * @author javaprogramto.com
 *
 */
public class DoWhileLoopInfiniteExample {
	public static void main(String[] args) {

		// do-while loop condition to true.
		do  {
			// core logic
			System.out.println("Running do-while loop");
		} while(true);
	}
}

5. Conclusion


In this article, We've seen how to create infinite loops in java in several ways.



1 comment:

Please do not add any spam links in the comments section.