While loop in Java

The While Loop is used to execute block of code or instructions repeatedly. while loop executes until the specified condition is true.

Syntax

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


While loop in Java

package com.yawintutor;

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

Output

0
1
2
3
4
5
6
7
8
9


Nested while loop in Java

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

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

package com.yawintutor;

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

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 while loop in Java

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

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

package com.yawintutor;

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

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

Output

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



Related Articles

Leave a Reply

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