Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

while — a pre-test loop

The while keyword introduces a loop that checks its condition before each execution of its body. The body may never execute; the condition must have type boolean or Boolean.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

while (condition) {
    // statements
}

while is a reserved keyword, so it cannot be an identifier. Its syntax is while (condition) statement; braces group multiple statements.

The condition is checked before each iteration. true runs the body; false ends the loop. Unlike do, the body may never execute.

The condition requires boolean or Boolean, not a number. Unboxing a null value of type Boolean throws NullPointerException.

An unlabeled break targets the innermost enclosing loop or switch statement. A switch expression cannot be its target. A break that would transfer control out of a switch expression is a compile-time error. Unlabeled continue targets the nearest loop. In a while loop, it causes the condition to be reevaluated. In a basic for loop, the update expressions, if present, are evaluated before the condition is checked again, if one is specified. An enhanced for loop has no explicit condition to recheck: it proceeds to the next element, if there is one. Ensure termination is possible; an accidental semicolon in while (condition); creates an empty body.

Examples

public class Main {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 3) {
            System.out.println(count);
            count++;
        }
    }
}

Result

1
2
3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources