Search⌘ K
AI Features

while & do-while Loops

Explore how to implement while and do-while loops in Java. Understand their differences, syntax, and common pitfalls like infinite loops. Learn when to use each loop type effectively to control program flow and ensure code runs as intended.

Loops allow a programmer to execute the same block of code repeatedly.

The while loop

The while loop is really the only necessary repetition construct. It will keep running the statements inside its body until some condition is met.

The syntax is as follows:

Java
while ( condition ) {
//body
}

The curly braces surrounding the body of the while loop indicate that multiple statements will be executed as part of this loop.

Here’s a look at the while loop code:

Java
class HelloWorld {
public static void main(String args[]) {
int x = 0;
int y = 0;
while (x != 4) { // the while loop will run as long as x==4 condition is being met
y += x;
x += 1;
}
System.out.println("Value of y = " + y);
System.out.println("Value of x = " + x);
}
}

Below is an illustration of the code above to help ...