Program Flow  «Prev  Next»
Lesson 7Using while loops
Objective Learn how to use while loops.

Using Java while Loops

Why use a while loop in favor of a for loop

If a for loop can do everything a while loop can and in a more structured fashion, then why would you ever want to use a while loop?
Because there are situations where you have no need for initialization and step expressions.
A for loop simply is not required in situations where initialization and step expressions occur at the beginning of the code block and ultimately makes the code harder to understand.
A while loop is much more readable than a for loop when you have no need for initialization and step expressions. Even though either loop can accomplish the job of repeating code, there certainly are situations where one is more suitable to the task than the other.
As you gain experience with Java, you will naturally develop an ability to determine which loop will work best in a given situation.
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) {
 statement(s)
}


Java while Statement

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:

class WhileDemo {
 public static void main(String[] args){
  int count = 1;
  while (count < 11) {
   System.out.println("Count is: " + count);
   count++;
  }
 }
}

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

The while loop is another type of loop similar to the for loop in that it has a loop condition that controls the number of times it is repeated. However, the while loop has no initialization or step expression.
The while statement provides an alternate way of repeatedly executing a block of statements. It is frequently used when the number of times the block is to be executed is not known. Its general form consists of the while keyword followed by a set of parentheses enclosing a logical expression and then a statement. The body of the loop will execute as long as the logical expression evaluates to true. Following is the syntax for the while loop:


while (LoopCondition)
  Statement

while (<boolean-expression>) <statements>;

A simple example duplicates the first for loop example where we display the numbers 1 to 10 on a single line:
int i = 1;
while(i <= 10) {
System.out.print(i++ + " ");
}
System.out.println();

The output is as follows:
1 2 3 4 5 6 7 8 9 10


The following example computes the factors of the number variable:
int number;
int divisor = 1;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
number = scanner.nextInt();
while (number >= divisor) {
 if ((number % divisor) == 0) {
  System.out.printf("%d%n", divisor);
 }
divisor++;
}

When executed with the input as 6, we get the following output:
Enter a number: 6
1
2
3
6

The following table illustrates the action of the statement's sequence:
While loop iteration Count >
While loop iteration Count

If the Boolean LoopCondition evaluates to true, the Statement is executed. The LoopCondition is then tested again and the process repeats itself until the LoopCondition evaluates to false. At that point the loop immediately exits.
Since the while loop has no step expression, you have to make sure that the Statement somehow alters the LoopCondition. If you do not, it is possible for the loop to infinitely repeat, which is usually a bad thing.
You can think of the while loop as a general for loop. The following code demonstrates what is meant by this comparison:

int i = 1;
while (i <= 10) {
  System.out.println(i);
  i++;
}


This is the same count example you saw earlier in the module implemented with a while loop. Since while loops do not have initialization expressions, the initialization of the counter variable i must be performed before entering the loop. Similarly, the step expression i++ must be performed within the Statement part of the loop. This while loop is functionally equivalent to the for loop you saw in the previous lesson.

While Loops - Exercise

Practice using the while loop in this exercise.
While Loops - Exercise

Java 12 Pogramming