The while Statement

🙋 Need help? Ask an expert now!

In addition to the for loop, the while loop achieves similar results. Examine the code below, which tackles the same printing problem as our example from the for loop. Note down any similarities or differences between the two.

WhileLoopExample.java
package exlcode;

public class WhileLoopExample {

  public static int exampleVariableOne = 0;
  public static int exampleVariableTwo = 10;

  public static void main(String[] args) {
    // while loop does not end until the boolean expression
    // is false
    System.out.println("Counting forward from 0-10:");
    while (exampleVariableOne <= 10) {
      System.out.print(exampleVariableOne + " ");
      exampleVariableOne++;
    }
    System.out.println("\nCounting backward from 0-10:");
    while (exampleVariableTwo >= 0) {
      System.out.print(exampleVariableTwo + " ");
      exampleVariableTwo--;
    }
  }
}

The code above contains two while statements, both followed by a block of code. A block is a group of statements enclosed within curly braces.

Let's examine the first while loop to see how the statement works. The expression inside the parenthesis is evaluated each time the loop is executed. If the result is "true", the while loop executes the statements. If the result is "false" the while loop terminates. So, if we were to explain the while loop in words: "while exampleVariableOne is less than or equal to 10, print the number and increment exampleVariableOne by one.

Make sure your while loop has a termination point after a certain amount of executions. Otherwise, the program will not run as intended and may crash.

Edit Me on GitHub!

Application Question

Consider the following code segment:

int varOne = 3;
            int varTwo = 2;
            int varThree = 0;
            while (varOne <= 5){
              varThree += varOne % varTwo;
              varOne++;
              varTwo++;
            }
            

What is the value of varThree after the code is executed?