Curriculum
In Java, the while loop is a control flow statement that allows you to execute a block of code repeatedly as long as a certain condition is true. The syntax of a while loop is as follows:
while (condition) {
// code to be executed while condition is true
}
The condition is an expression that is tested at the beginning of each iteration of the loop. If the condition is true, the code inside the loop is executed. This continues until the condition becomes false, at which point the loop terminates and control is transferred to the statement following the loop.
Here’s an example of a simple while loop:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
In this example, the while loop iterates as long as i is less than 5. During each iteration, the value of i is printed to the console, and then i is incremented by 1. The loop will terminate when i is equal to 5.
Another use of a while loop is to read input from the user until a specific condition is met. Here’s an example:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
System.out.print("Enter a command (or 'quit' to exit): ");
input = scanner.nextLine();
// process the command here
}
scanner.close();
In this example, the while loop continues to prompt the user to enter a command until the user enters the word “quit”. The loop will then terminate, and the program will continue executing.
It’s important to make sure that the condition used in a while loop eventually becomes false, or the loop will continue to execute indefinitely, leading to an infinite loop. Infinite loops can cause your program to crash or become unresponsive, so it’s important to use conditions that will eventually become false.