Java While Loop

A while statement executes a block of statements until the condition satisfied. A Boolean expression (condition) is tested before each iteration of the loop. When we want to execute a number of lines, multiple times based on a condition we use while loop.

Here this flow chart will describe a while loop better-


Java While Loop, Java While Loop Example

Syntax

while(condition){  
//code to be executed  
} 

public class mywhileloop {  
public static void main(String[] args) {  
    int d=1;  
    while(d<=20){  
        System.out.println(d);  
    d++;  
    }  
}  
}
Example Output

Java Infinite While Loops

An infinite while loop in Java is a set of code that would repeat itself forever unless the system crashes.

Syntax

while(true){
	// your code here
}

We can implement an infinite loop using a while statement-

Note: ctrl+c to exit from the program

public class demoinfinitive {  
public static void main(String[] args) {  
    while(true){  
        System.out.println("Java Point Tutorial");  
    }  
}  
}
Example Output

Java While Loop Array List Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class MyWhileLoop {

	public static void main(String args[]) {
		List ac = new ArrayList();

		ac.add("Tom");
		ac.add("Johny");
		ac.add("Micheal");
		ac.add("Ricky");
		ac.add("San");
		ac.add("Kivi");

		Collections.sort(ac);
		Iterator it = ac.iterator();

		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}

}
Example Output

Share