How to Use While Statements in Java

A while statement in Java programming creates a loop that executes continuously as long as some conditional expression evaluates to true. The basic syntax is this:

while (expression)

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.

You can exit the middle of a loop by using a break statement. You can also use a continue statement to skip an execution of the loop.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.