The while
loop in Java allows you to execute a block of code repeatedly as long as a specified condition is true. It is one of the simplest and most useful loops in programming.
Syntax of While Loop
while (condition) {
// Code block to be executed
}
condition
: The condition is checked before each iteration. If the condition evaluates to true, the code inside the loop is executed. The loop continues until the condition becomes false.- The loop will not execute if the condition is initially false.
Basic Example of While Loop
Let’s look at a simple example where we print the numbers from 1 to 5 using the while
loop:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // Incrementing i by 1
}
}
}
Output:
1
2
3
4
5
In this example, the loop continues as long as the condition i <= 5
is true. Once i
exceeds 5, the loop terminates.
How the While Loop Works:
- The condition is evaluated before entering the loop.
- If the condition is true, the code block is executed.
- After each iteration, the condition is checked again.
- If the condition is still true, the code block runs again.
- The loop ends when the condition becomes false.
Infinite While Loop
If the condition of a while loop is always true, the loop will run indefinitely. This is known as an infinite loop.
public class InfiniteLoop {
public static void main(String[] args) {
while (true) {
System.out.println("This will print forever!");
}
}
}
Output:
This will print forever!
This will print forever!
...
Infinite loops should be avoided unless explicitly required, and they can be stopped with Ctrl + C in the terminal or through a condition that breaks the loop.
Using break
and continue
in While Loops
The break
and continue
statements can also be used within the while
loop to control the flow:
break
: Exits the loop immediately.continue
: Skips the current iteration and moves to the next iteration of the loop.
Example with break
public class BreakExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
if (i == 3) {
break; // Exits the loop when i is 3
}
System.out.println(i);
i++;
}
}
}
Output:
1
2
Example with continue
public class ContinueExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
i++;
if (i == 3) {
continue; // Skips printing 3
}
System.out.println(i);
}
}
}
Output:
2
4
5
Do-While Loop: A Variation of the While Loop
The do-while
loop is a variation where the loop’s code block is executed at least once before checking the condition.
Syntax of do-while Loop
do {
// Code block to be executed
} while (condition);
In a do-while
loop, the condition is checked after executing the loop, ensuring that the code runs at least once, even if the condition is false at first.
Example: Do-While Loop
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
Output:
1
2
3
4
5
Even though the condition is checked after the code block is executed, the result is similar to a while loop in this case.
Real-Life Example: User Input with While Loop
A common use of the while loop is to repeatedly ask for user input until a valid input is provided.
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userInput;
System.out.println("Enter a positive number:");
userInput = sc.nextInt();
while (userInput <= 0) {
System.out.println("Invalid input! Please enter a positive number:");
userInput = sc.nextInt();
}
System.out.println("You entered: " + userInput);
sc.close();
}
}
Output:
Enter a positive number:
-5
Invalid input! Please enter a positive number:
10
You entered: 10
In this example, the loop continues until the user enters a valid positive number.
Key Points to Remember About While Loop
- The
while
loop tests the condition before executing the code block. - If the condition is false at the start, the code block won’t execute at all.
- Always ensure that the loop condition will eventually become false; otherwise, it will result in an infinite loop.
- Use
break
to exit the loop prematurely andcontinue
to skip an iteration.
With the while
loop, you can handle repetitive tasks efficiently in your Java programs. It provides the flexibility to iterate until a condition is met, making it an essential tool for managing flow in programming.
For more insights and practical coding tips, visit Master Coding Science at mastercodingscience.com.