Java while & do...while loop
In this tutorial, we will learn how to use while and do while loop in Java with the help of examples.
In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then you can use a loop.
In the previous tutorial, you learned about Java for loop. Here, you are going to learn about while and do...while loops.
1. Java while loop
Java while loop is used to run a specific code until a certain condition is met. The syntax of the while loop is:
while (condition) {
// body of loop
}Here,
- A
whileloop evaluates the condition inside the parenthesis(). - If the condition evaluates to
true, the code inside thewhileloop is executed. - The condition is evaluated again.
- This process continues until the condition is
false. - When the condition evaluates to
false, the loop stops.
Example 1: Display Numbers from 1 to 5
// Program to display numbers from 1 to 5
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
// while loop from 1 to 5
while(i <= n) {
System.out.println(i);
i++;
}
}
}Output:
1
2
3
4
52. Java do...while loop
The do...while loop is similar to while loop. However, the body of do...while loop is executed once before the test expression is checked.
do {
// body of loop
} while(condition);Example 2: Input Validation
The do...while loop is perfect for asking user input until they give a valid response.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Enter a positive number: ");
number = input.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
}
}Here, the loop will keep asking for a number at least once, and repeat if the user enters a negative number or zero.
3. Infinite Loops
If the condition of a loop is always true, the loop runs for infinite times.
// infinite while loop
while(true){
// body of loop
}Key Takeaways
- While: Checks condition before running. Might not run at all.
- Do-While: Checks condition after running. Always runs at least once.
- Use Case: Best when you don't know the number of iterations (e.g., reading user input until they type "exit").
Common Pitfalls
[!WARNING] Infinite Loops: It's very easy to forget to update your counter (e.g.,
i++) inside a while loop, causing it to run forever.
[!WARNING] Semicolon: The
do...whileloop MUST end with a semicolon;after the condition.do { } while(condition);
Challenge
Challenge
Task:
Write a while loop that prints numbers from 5 down to 1.