Java While Loop

A block of code can be run by a loop as long as a predetermined condition is met.

Loops are useful because they eliminate errors, save time, and improve readability of programming.

Java While Loop

A block of code is iterated through by the while loop as long as a particular condition is met:

Syntax

				
					while (condition) {
  // code block to be executed
}
				
			

In the example below, if a variable (i) is less than 5, the loop’s code will continue to run repeatedly:

Example

				
					int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}
				
			

Note: If you don’t increment the variable in the condition, the loop will never stop!

Share this Doc

While Loop

Or copy link

Explore Topic