While Loop

The while loop is a fundamental control flow statement in Java that allows repeated execution of a block of code as long as a specified condition evaluates to true. It is particularly useful when the number of iterations is not known in advance but is instead dependent on a dynamic condition.

Syntax

The basic syntax of the while loop in Java is as follows:

  • while Keyword: This initiates the loop.
  • Condition: A boolean expression that is evaluated before each iteration. If the condition is true, the loop body executes. If the condition is false, the loop terminates.
  • Body: The block of code enclosed within curly braces {} that will execute repeatedly as long as the condition is true.

Note: If the condition is initially false, the loop body will not execute even once. This is known as an “entry-controlled loop.”

Example

  • Initialization: The variable number is initialized to 1 before the loop starts.
  • Condition: The while loop checks if number is less than or equal to 5.
  • Execution: Inside the loop, the value of number is printed.
  • Update: The number variable is incremented by 1 using number++.
  • Termination: When number becomes greater than 5, the condition evaluates to false, and the loop exits.

Output

Infinite while loop

If the condition in a while loop never becomes false, the loop runs indefinitely, causing an infinite loop.

To avoid infinite loops, ensure that the condition eventually becomes false by modifying variables involved in the condition within the loop.