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:
Java
1 2 3 |
while (condition) { // Code to be executed repeatedly } |
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 isfalse
, the loop terminates. - Body: The block of code enclosed within curly braces
{}
that will execute repeatedly as long as the condition istrue
.
Note: If the condition is initially false
, the loop body will not execute even once. This is known as an “entry-controlled loop.”
Example
Java
1 2 3 4 5 6 7 8 9 10 11 |
public class WhileLoopExample { public static void main(String[] args) { int number = 1; // Initialize the variable // Start the while loop while (number <= 5) { System.out.println("Number: " + number); number++; // Increment the variable } } } |
- Initialization: The variable
number
is initialized to 1 before the loop starts. - Condition: The
while
loop checks ifnumber
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 usingnumber++
. - Termination: When
number
becomes greater than 5, the condition evaluates tofalse
, and the loop exits.
Output
Java
1 2 3 4 5 |
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 |
Infinite while loop
If the condition in a while
loop never becomes false
, the loop runs indefinitely, causing an infinite loop.
Java
1 2 3 |
while (true) { System.out.println("This is an infinite loop."); } |
To avoid infinite loops, ensure that the condition eventually becomes false
by modifying variables involved in the condition within the loop.