Java do while loop

The Article is about the use of Java do while loop.

The Java do while loop, like the for loop and while loop, has a condition which defines it’s termination point. However, unlike them it checks its condition at the bottom of the loop instead of the top.

This results in the do while loop always running once no matter the condition being True or False, unlike the while loop, which will not run at all if the condition is false.

Syntax

Below is the general syntax for the Java do while loop.

do {
  // statements
}
while(condition)

Example

A basic example of the Java do while loop. Other supporting code was removed to improve readability and keep the code short.

int x = 0;

do {
    System.out.println(x);
    x = x + 1;
}
while (x < 5);
0
1
2
3
4

As of this point, the do while loop still seems to be identical to the while loop. We’ll now show an example where both of them act differently.


Example 2

The following code makes use of the Java Scanner module to take input from the user.

import java.util.Scanner;

public class example {
	public static void main(String[] args) 	{		
		int x;
		int sum = 0;
		
		System.out.println("Input a negative number to exit");
		Scanner scan = new Scanner(System.in);
		
		do {
		  x = scan.nextInt(); //takes input from user
		  sum = sum + x;      
		  System.out.println(sum);
		}
	        while(x > 0);
		
	        System.out.println(sum);
	}
}

The above code is designed to keep taking input from the user, adding them up in the variable sum until a negative number is input to terminate the loop.

The use of the do while loop is important here as the code must run once so that the value of x can be obtained to be matched against the condition. This is contrast to the while loop, which would first check the condition and throw an error since x has no value at that point.

If you don’t understand how we’re taking input here, see the Java input guide. It’s just a better way of taking input than System.in.read().


Using Multiple Statements

Using the and operator && we can connect two conditions together. Chaining two conditions together with && ensures the loop only runs when both conditions are true, and will terminate if any of them becomes false.

public class example {
	public static void main(String[] args) 	{		
		int x = 0;	
		int y = 0;
		
		do  {
		    x = x + 1;
		    y = y + 2;
		    System.out.println("X: " + x + " " + "Y: " + y);
		}    
		while (x < 5 && y < 6);    		     			
	}
}

The above loop stops after the value of y reaches 6, even though x was still less than 5.

You can use other operators like the or and xor to change things up. See the Java Operators guide to learn more.


Loop control statements

There are several loop control in Java, that as the name implies, can be used to manipulate the do while loop during it’s execution.

continue statement

The continue statement, when encountered will skip any remaining lines of code in the current iteration of the loop and skip to the beginning of the next iteration.

We’ll be modifying a portion of the code from one of the previous examples here. In this example, we want to write a program that takes the sum of all the positive odd numbers.

do {
     x = scan.nextInt(); //takes input from user
     if (x % 3 == 0) continue;
     sum = sum + x;      
     System.out.println(sum);
}
while(x > 0);

When an even number is input and evaluated by the mod function, it’s remainder will be zero. Since the if condition came true, the continue statement will activate, skip the next two lines and go back to the start of the loop. Only odd numbers will be allowed through.

Break statement

The break statement when called, terminates a loop during it’s execution. It is an effective way of forcing your loop to stop if some unexpected outcome has been encountered.

import java.util.Scanner;

public class example {
	public static void main(String[] args) 	{		
		int x;
		int count = 0;		

		Scanner scan = new Scanner(System.in);		
		do {
		  x = scan.nextInt();
		  if (x < 0) {
		     System.out.println("Please input positive numbers");
		     break;
		  }
		  count = count + 1;
		  System.out.println(x);
		}
	    while(count < 5);		
	}
}

The above code runs for a total of 5 times, taking input of positive numbers from the user. To ensure the user doesn’t input a negative number, we use a if statement that leads to a break statement and an error message. When the user inputs a negative number, the error message is printed and the loop terminates due to the break statement.

5
5
2
2
-6
Please input positive numbers

This marks the end of the Java do while loop article. Any suggestions or contributions for CodersLegacy are more than welcome. You can ask any relevant questions in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments