FreeCode

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

Do-While Loops

Code Description:

Do-While loops are similar to the While Loop. They will iterate through their loop body until their condition no longer evaluates to true. However, these loops check if the condition evaluates to true after the loop has already went through an initial iteration. These loops therefore should be used when you need to execute something at least once but don't know how many times after that.

Do-While Loop Syntax:

boolean condition = true;		
do {
    // Perform actions here until the condition evaluates to false. This code will execute at least once.
} while (condition);

Runnable Do-While Loop Example Code:

public class Demo {

    public static void main(String[] args) {

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

}

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.

Output:

Do-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:

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