While Loop in Java
In Java, a while
loop is a control flow statement that allows you to execute a block of code repeatedly as long as a certain condition is true. The while
loop continues to execute the code block as long as the condition is true, and it stops executing the code block when the condition becomes false.
Here is the basic syntax for a while
loop in Java:
while (condition) {
// code to be executed
}
The condition
is a boolean expression that is evaluated before each iteration of the loop. If the condition is true
, the code block within the loop is executed. If the condition is false
, the loop is terminated and control is passed to the next statement after the loop.
Here is an example of a while
loop in Java that counts down from 10 to 0:
int count = 10;
while (count >= 0) {
System.out.println(count);
count--;
}
System.out.println("Done!");
Output:
10
9
8
7
6
5
4
3
2
1
0
Done!
This loop would print the numbers 10, 9, 8…until it reaches 0 where it would exit the loop and then print the word “Done!”.
Here is an example of the samewhile
loop but counting from 0 to 10:
int count = 0;
while (count <= 10) {
System.out.println(count);
count++;
}
System.out.println("Done!");
Output:
0
1
2
3
4
5
6
7
8
9
10
Done!
This loop would behave similarly except it would print the numbers 1, 2, 3…until it reaches 10 where it would exit the loop and then print the word “Done!”.
This code defines a variable count
and initializes it to 10. The while
loop is then used to execute a code block that prints the value of count
and decrements count
by 1. The loop continues to execute as long as count
is greater than 0, and it stops executing when count
becomes 0. After the loop has finished executing, the code prints "Done!"
The while
loop is an important control flow statement in Java, and it is often used when you need to execute a block of code repeatedly based on a specific condition. It is particularly useful when you do not know in advance how many times you need to execute the loop.
Find out more about Java here: