Do While loop in Java

The Do While Loop is used to execute block of code or instructions repeatedly. Do while loop executes at least once before checking the condition. Do while loop executes until the specified condition is true.

syntax

initialization statement
do {
  // block of code to execute multiple times
  
  increment/decrement statement
} while(condition);


Do While loop in Java

package com.yawintutor;

public class DoWhileLoop {
	public static void main(String[] args) {
		int i = 0;
		do {
			System.out.println(i);
			i++;
		} while (i < 10);
	}
}

Output

0
1
2
3
4
5
6
7
8
9


Nested do while loop in Java

A do while loop is created inside another do while loop is called nested do while loop. Nested do while loops are commonly used to iterate multi-dimensional data.

If outer do while loop is configured to run n times, inner do while loop is configured to run m times, then the code within inner do while loop runs n x m times.

package com.yawintutor;

public class NestedDoWhileLoop {
	public static void main(String[] args) {
		int i = 1;
		do {
			System.out.println("\nSTART OUTER FOR i = " + i);
			int j = 1;
			do {
				System.out.println("i = " + i + " j = " + j);
				j++;
			} while (j <= 3);
			System.out.println("END   OUTER FOR i = " + i);
			i++;
		} while (i <= 3);
	}
}

Output


START OUTER FOR i = 1
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
END   OUTER FOR i = 1

START OUTER FOR i = 2
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
END   OUTER FOR i = 2

START OUTER FOR i = 3
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3
END   OUTER FOR i = 3


Infinite do while loop in Java

The do while loop allows to execute the block of code by infinite times. In do while condition, just specify “true” in the condition, then the do while loop executes infinite time.

Infinite while loops can be stopped by killing the process. (Cntr + C)

package com.yawintutor;

public class InfiniteDoWhileLoop {
	public static void main(String[] args) {
		int i = 0;

		do {
			System.out.println(i++);
		} while (true);
	}
}

Output

0
1
2
3
4
5
6
.
.
.
.
.



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *