Infinite loop in Java
1. Introduction
This is an in-depth article related to the Infinite loop in java. Infinite loop is a task which loops without any stopping condition. Typically this happens as an error or intentional requirement. This can be achieved or happens in a for, while, and do while loops. A loop has a start and end condition. Infinite loops do not have the end condition.
2. Infinite Loop
2.1 Prerequisites
Java 7 or 8 is required on the linux, windows or mac operating system. Maven 3.6.1 is required for building the spring and hibernate application.
2.2 Download
You can download Java 8 can be downloaded from the Oracle web site .
2.3 Setup
You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:
Setup
JAVA_HOME="/desktop/jdk1.8.0_73" export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH
2.4 Using while
Let us look at the while loop where true is set as non terminating condition to execute tasks. Below is the pseudo code.
While Loop
public class ExampleWhileLoop { public static void main(String[] args) { while (true) { // execute tasks } } }
2.5 Using for
Now let us look at the for loop with no start or ending condition. Below is the sample code.
For Loop
public class ExampleForLoop { public static void main(String[] args) { for(;;) { // execute tasks } } }
2.6 Using do-while
Now let us look at the same in do while loop. True is set as a non terminating condition
Do While Loop
public class ExampleDoWhileLoop { public static void main(String[] args) { do { // execute tasks } while (true); } }
2.7 Example – Web Server
A typical web server serves for different requests and returns the response based on the processing logic for a request. This is done in a infinite loop. Let us look at the pseudo code using while, for, and do-while loop
While Loop
public class WebServer { public static void main(String[] args) { while ( true ) { // Read request // Process request } Another popular way is: for ( ; ; ) { // Read request // Process request } do { // Read request // Process request } while(true); } }
3. Download the Source Code
You can download the full source code of this example here: Infinite loop in Java