java
  1. java-while-loop

Java While Loop

Syntax

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

Example

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

Output

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

Explanation

In Java, a while loop is used to execute a block of code repeatedly until a certain condition is met. It consists of a condition and a loop body. The loop body will continue to execute until the condition becomes false.

In the above example, the loop body will execute as long as the variable i is less than 5. The loop body will print the value of i and increment it by 1 in each iteration. The loop will terminate when i becomes equal to 5.

Use

While loops are commonly used for iterative tasks in Java. They are particularly useful when you do not know the exact number of times a task needs to be performed.

Some common use cases for while loops include reading input from a user until a certain condition is met, iterating through arrays or lists, and performing calculations until certain conditions are met.

Important Points

  • The condition in a while loop must be a boolean expression.
  • The loop body will continue to execute until the condition becomes false.
  • It is important to avoid infinite loops, where the loop body never terminates due to an incorrect or missing condition.
  • The loop variable (if used) must be updated within the loop body to ensure the loop will eventually terminate.

Summary

In Java, a while loop allows you to execute a block of code repeatedly until a certain condition is met. It is a useful tool for performing iterative tasks in your programs. Remember to always include a boolean expression in your condition, update your loop variable (if used) within the loop body, and ensure the loop will eventually terminate.

Published on: