Java While Loop
The while
loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop continues to execute as long as the specified condition evaluates to true
. It is particularly useful when the number of iterations is not known beforehand.
Syntax
while (condition) {
// Code to be executed
}
condition
: A boolean expression evaluated before each iteration. Iftrue
, the loop body is executed; iffalse
, the loop terminates.
Examples
Example 1: Basic while
Loop
public class WhileExample {
public static void main(String[] args) {
int count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
}
}
In this example, the while
loop prints the value of count
as long as it is less than 5. The count
variable is incremented in each iteration, ensuring that the loop eventually terminates.
Example 2: Infinite while
Loop
public class InfiniteLoopExample {
public static void main(String[] args) {
while (true) {
System.out.println("This is an infinite loop.");
break; // To prevent an actual infinite loop
}
}
}
This example demonstrates an infinite while
loop, where the condition is always true
. The break
statement is used here to exit the loop, preventing it from running indefinitely.
Example 3: Using while
Loop for Input Validation
import java.util.Scanner;
public class InputValidationExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
System.out.println("Enter a number between 1 and 10:");
number = scanner.nextInt();
while (number < 1 || number > 10) {
System.out.println("Invalid input. Please enter a number between 1 and 10:");
number = scanner.nextInt();
}
System.out.println("You entered: " + number);
}
}
In this example, the while
loop is used to validate user input. It continues to prompt the user until a valid number between 1 and 10 is entered.
Tips and Best Practices
- Avoid Infinite Loops: Ensure that the loop condition will eventually become
false
to avoid infinite loops, unless intentionally used with proper control mechanisms likebreak
. - Use
break
andcontinue
Wisely: Usebreak
to exit a loop prematurely if necessary, andcontinue
to skip the current iteration and proceed to the next one. - Keep Conditions Simple: Write simple and clear conditions to improve readability and maintainability.
- Monitor Performance: Be cautious with loops that may result in high computational costs or memory usage, especially when dealing with large datasets or complex operations.
- Debugging: Use print statements or a debugger to trace loop execution and ensure it behaves as expected, particularly during development and testing phases.