Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

While Loops

Code Description:

While loops are the most basic type of loop. They will iterate through their loop body until their condition no longer evaluates to true. These should be used when you do not have a specific number of times you need to iterate through your loop body.

While Loop Syntax:

boolean condition = true;		
while (condition) {
    // Perform actions here until the condition evaluates to false

Runnable While Loop Example Code:

public class Demo {

    public static void main(String[] args) {

	boolean condition = true;
	int loopCount = 1;
	while (condition) {
	    System.out.println("Loop Iteration: " + loopCount);
	    if (loopCount == 6) {
		condition = false;


How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.


While Loop Output Image

Important Notes:

  • The "break" keyword can be used in a loop to fully terminate its execution at any point.
  • The "continue" keyword ends the current iteration of a loop immediately and moves onto the next iteration.
  • Be careful and make sure that the condition for the loop will eventually become set to false. If it is not, you will have an infinite loop.

Related Links:

Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements