Back to: Java Tutorials
A while
loop is a control flow statement that allows you to execute a block of code repeatedly as long as a given condition is true. The syntax for a while
loop in Java is as follows:
while (condition) {
// code to be executed
}
The condition
is an expression that is tested at the beginning of each iteration of the loop. If the condition
is true, the code inside the loop is executed. After the code inside the loop is executed, the condition
is tested again, and the loop continues as long as the condition
remains true.
Here is an example of a while
loop that prints the numbers 1 to 5:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
In this example, the while
loop is used to print the numbers 1 to 5. The loop condition is i <= 5
, which is true for the values of i
from 1 to 5. Inside the loop, the value of i
is printed using System.out.println(i)
, and then incremented using i++
. This means that the loop will continue to execute as long as i
is less than or equal to 5, and the values of i
printed will be 1, 2, 3, 4, and 5.
It’s important to note that if the condition
in a while
loop is never false, the loop will continue to execute indefinitely, which can cause your program to hang or crash. To prevent this, it’s important to ensure that the condition
will eventually become false, either through changes in the program state or through external events. Additionally, you should always ensure that the condition
is tested properly and that the loop body will eventually change the program state in a way that makes the condition
false.
Complete code example:
Here is an example of using a while
loop in Java to print the even numbers between 1 and 10:
package whileL_loop;
/**
* An example of using a while loop in Java to print the even numbers between 1
* and 10
*
* @author Mamun Kayum
*
*/
public class JavaWhileLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i % 2 == 0) {
System.out.println(i);
}
i++;
}
}
}
In this example, the while
loop starts with an initial value of i = 1
. The loop condition i <= 10
is checked at the beginning of each iteration to determine if the loop should continue or exit. Inside the loop, the if
statement checks if the current value of i
is even by using the modulo operator %
to check if i
is evenly divisible by 2. If i
is even, the System.out.println(i)
statement is executed to print the value of i
. The i++
statement increments i
by 1 at the end of each iteration to prepare for the next iteration.
When you run this code, it will print the even numbers between 1 and 10, which are 2, 4, 6, 8, and 10. Note that the loop will not print any odd numbers because the if
statement inside the loop only prints even numbers.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author