while Statement
A while
statement creates a loop that executes continuously as long as some conditional expression evaluates to true
. The basic syntax is this:
while (expression)
statement
The while
statement begins by evaluating the expression. If the expression is true
, statement
is executed. Then the expression is evaluated again, and the whole process repeats. If the expression is false
, statement
is not executed, and the while
loop ends.
Note: The statement part of the while
loop can either be a single statement or a block of statements contained in a pair of braces.
Here’s a snippet of code that uses a while
loop to print the even numbers from 2 through 20 on the console:
int number = 2;
while (number <= 20)
{
System.out.print(number + “ “);
number += 2;
}
If you run this code, the following output is displayed in the console window:
2 4 6 8 10 12 14 16 18 20
The conditional expression in this program’s while
statement is number
<=
20
. That means the loop repeats as long as the value of number
is less than or equal to 20
. The body of the loop consists of two statements. The first prints the value of number
, followed by a space to separate this number from the next one. Then the second statement adds 2 to number
.
Get Java For Dummies Quick Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.