Start Coding Now

While Loop in Java - Syntax and Examples

Learn about while loops in Java. Execute code repeatedly as long as a condition is true.

While Loop

Loops through a block of code as long as a specified condition is true.

while (condition) {
    // code block
}

Example

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

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end (infinite loop).

Frequently Asked Questions