![]() |
VOOZH | about |
Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed.
Let's go through a simple example of a Java while loop:
1 2 3 4 5
Explanation: In this example, it prints the numbers from 1 to 5 by repeatedly executing the loop as long as the counter variable "c" is less than or equal to 5.
while (condition) {
// statements to execute repeatedly
// (updates to loop variables must be inside the loop body)
}
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after while( condition ), then by default while statement will consider the immediate one statement to be inside its block.
Now, let's understand the execution flow of while loop with the below diagram:
Below are the examples of Java while loop that demonstrates repeating actions and performing calculations.
Example: Repeating a Message with while loop
Hello World Hello World Hello World Hello World Hello World
Explanation: In the above example, the while loop runs until "i" is less than 6 and prints "Hello World" 5 times.
Example: Calculating the Sum of Numbers from 1 to 10 with Java while Loop
Summation: 55
Explanation: This program finds the summation of numbers from 1 to 10.