Site icon TestingDocs.com

Java do while loop statement

Overview

In this tutorial, we will learn the do-while loop statement. In this loop statement, the loop condition is checked at the end of the loop.

Java while Loop

https://www.testingdocs.com/java-while-loop-statement/

do while Loop

This loop checks the loop condition after executing the loop statements. (post-check loop control). The loop statements will execute at least once even if the loop condition evaluates to false.

The do-while loop is guaranteed to execute the loop statements at least once. So, this loop is ideal for menu-based user programs. We can display the application menu in the loop and let the user decide the flow of the program.

do
{
// loop Statements
}
while(boolean loop condition);

 

Example

In the below example, we will use a do-while loop to display a menu to the user. The program takes actions based on the user input to the program.

public class DoWhileLoopDemo {
	
	public static void main(String[] args) {
		int choice = 0;
		Scanner keypad = new Scanner(System.in);
		do {
			System.out.println("--- Menu ---");
			System.out.println("1.Task1");
			System.out.println("2.Task2");
			System.out.println("3.QUIT");
			System.out.println("Enter choice:");
			choice = keypad.nextInt();
			if(choice == 1)
				System.out.println("Perform Task1 
for user.");
			if(choice == 2)
				System.out.println("Perform Task2 
for user.");
		}while(choice == 1 || choice == 2);
	}
}

 

Sample Program Output

— Menu —
1.Task1
2.Task2
3.QUIT
Enter choice:
1
Perform Task1 for user.
— Menu —
1.Task1
2.Task2
3.QUIT
Enter choice:
2
Perform Task2 for user.
— Menu —
1.Task1
2.Task2
3.QUIT
Enter choice:
3

 

The loop will run many times as per the user’s choice. The loop will run if the user choice is 1 or 2. The loop will terminate for any other user option.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version