Introduction to While Loop
The while loop in Java is a control flow statement used to repeatedly execute a block of code as long as a specified condition is true. It is one of the most fundamental looping constructs in Java, making it ideal for situations where the number of iterations is not fixed or known beforehand.
With a while loop, you can execute code blocks efficiently without redundancy, enabling more concise and maintainable programs.
Syntax of While Loop
while (condition) {
// Code to execute repeatedly
}
Key Points About While Loop
- Condition Evaluation:
- The loop condition must return a boolean value (true or false).
- If the condition evaluates to true, the code inside the loop executes.
- If the condition evaluates to false, the loop terminates.
- Entry-Controlled Loop:
- The condition is checked before executing the loop body. If the condition is false at the beginning, the loop does not execute even once.
- Infinite Loops:
- A while loop can lead to an infinite loop if the condition never evaluates to false. To avoid this, ensure the condition is updated correctly within the loop.
Flowchart for While Loop
- Check the condition.
- If the condition is true, execute the loop body.
- Re-evaluate the condition after completing one iteration.
- If the condition is false, exit the loop.
Examples of While Loop
Example 1: Print Numbers from 1 to 5
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++; // Increment i to avoid infinite loop
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 2: Calculate the Sum of Natural Numbers
public class SumNaturalNumbers {
public static void main(String[] args) {
int number = 10; // Calculate sum of numbers from 1 to 10
int sum = 0;
int i = 1;
while (i <= number) {
sum += i; // Add i to the sum
i++;
}
System.out.println("Sum of first 10 natural numbers is: " + sum);
}
}
Output:
Sum of first 10 natural numbers is: 55
Example 3: User Input with While Loop
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
while (true) {
System.out.print("Enter a command (type 'exit' to stop): ");
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
break; // Exit the loop if user types "exit"
}
System.out.println("You entered: " + input);
}
System.out.println("Program terminated.");
scanner.close();
}
}
Output:
Enter a command (type 'exit' to stop): Hello
You entered: Hello
Enter a command (type 'exit' to stop): exit
Program terminated.
Example 4: Infinite While Loop
public class InfiniteLoopExample {
public static void main(String[] args) {
while (true) {
System.out.println("This will run forever unless stopped!");
}
}
}
Note: The above example demonstrates an infinite loop. Use it cautiously and only in specific scenarios.
Common Mistakes and How to Avoid Them
- Forgetting to Update the Condition:
If the loop variable is not updated, the condition will never become false, resulting in an infinite loop. Always ensure that your loop includes logic to update the condition. - Incorrect Condition Logic:
Write conditions carefully to prevent off-by-one errors or premature termination. - Not Initializing Variables Properly:
Ensure loop variables are initialized before the loop starts.
Advantages of While Loop
- Flexibility:
- Ideal for scenarios where the number of iterations is not predetermined.
- Simplicity:
- Easy to implement and understand.
- Efficient for Certain Conditions:
- Especially useful when dealing with conditions like user inputs or sensor readings.