While Loop in Java
A while loop is used to repeatedly execute a block of code as long as a specified condition is true.
It checks the condition before executing the loop body, meaning the loop may not execute at all if the condition is false from the start.
It is a fundamental control structure in Java that allows you to execute a block of code repeatedly based on a given condition.
The while loop is particularly useful when the number of iterations is not known in advance and you want the loop to continue running as long as a specific condition is true.
Syntax of a while Loop
Here is the basic syntax of a while loop in Java:
while (condition) {
// code to be executed
}
- condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop terminates.
How It Works
Condition Check: The while loop evaluates the condition.
Loop Body: If the condition is true, the code block inside the loop is executed.
Repeat: After executing the loop body, the condition is evaluated again.
Termination: The loop continues to execute as long as the condition remains true. If the condition becomes false, the loop terminates.
This process repeats until the condition evaluates to false.
Example of a while Loop
Let's look at a simple example to understand how a while loop works. Consider the following code:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("Iteration: " + i);
i++;
}
}
}
Explanation:
Initialization: int i = 0; initializes the counter variable i to 0.
Condition: i < 5 is the condition that is checked before each iteration. The loop will continue to execute as long as i is less than 5.
Loop Body: System.out.println("Iteration: " + i); prints the current value of i to the console, and i++ increments the counter variable i by 1 after each iteration.
Since i starts at 0 and increments by 1 each time, the loop will run 5 times, producing the following output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Using a while Loop with User Input
A common use case for a while loop is to keep prompting the user for input until they provide a valid response. Here's an example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
while (true) {
System.out.print("Enter a number between 1 and 10: ");
number = scanner.nextInt();
if (number >= 1 && number <= 10) {
break;
} else {
System.out.println("Invalid input. Try again.");
}
}
System.out.println("You entered: " + number);
}
}
Explanation:
Infinite Loop: while (true) creates an infinite loop that will keep running until a break statement is encountered.
User Input: number = scanner.nextInt(); reads an integer input from the user.
Condition Check: if (number >= 1 && number <= 10) checks if the input is within the valid range.
Break Statement: If the input is valid, break; exits the loop.
Invalid Input: If the input is invalid, a message is printed, and the loop continues.
Summary
while loop: Repeatedly executes a block of code as long as a specified condition is true.
Syntax: while (condition) { // code }
Condition: A boolean expression evaluated before each iteration.
Loop Body: Code block executed if the condition is true.
Use Cases: Ideal for scenarios where the number of iterations is not known in advance.
Common Pitfalls: Be mindful of infinite loops and ensure the loop condition can eventually become false.
The while loop is a versatile and essential control structure in Java.