Loops are the backbone of repetitive tasks in programming, allowing you to execute a block of code multiple times without the need to duplicate it. Among the various types of loops in Java, the while
loop stands out as a versatile construct when you want to repeat a block of code based on a specific condition.
Let’s explore a basic example using a while
loop to count prices. In this scenario, we have a counter starting at 0, and we want to print “The price is” followed by the current counter value until the counter reaches 10.
public class WhileLoopExample {
public static void main(String[] args) {
int price = 0;
while (price < 10){
System.out.println("The price is " + price);
price++;
}
}
}
the output is:
The price is 0
The price is 1
The price is 2
The price is 3
The price is 4
The price is 5
The price is 6
The price is 7
The price is 8
The price is 9
1. The structure of a while statement
while (booleanExpression) {
// Code to be executed while the booleanExpression is true
}
while
Keyword: Initiates thewhile
loop.- (Boolean Expression): A condition that determines whether the loop should continue executing. As long as the boolean expression evaluates to
true
, the loop persists. The parenthesis are required - Curly Braces
{}
: Enclose the block of code to be executed as long as the boolean expression is true. While optional for a single statement, using braces is recommended for clarity and to avoid potential pitfalls.
1.1. Execution Flow
- The boolean expression is evaluated. If it is
true
, the loop body is executed. - The code within the loop is executed.
- The boolean expression is re-evaluated.
- Steps 2 and 3 are repeated until the boolean expression becomes
false
. - Once the boolean expression is
false
, the loop terminates, and program execution continues with the next statement after the loop.
public class WhileLoopWithTwoVariables {
public static void main(String[] args) {
int x = 5;
int y = 3;
while (x > 0 && y > 0) {
System.out.println("x: " + x + ", y: " + y);
x--; // Decrease the value of x
y--; // Decrease the value of y
}
System.out.println("Loop exited. x: " + x + ", y: " + y);
}
}
- Variables: We have two variables,
x
andy
, both initialized with values (x = 5
andy = 3
). - Boolean Expression: The
while
loop has a boolean expressionx > 0 && y > 0
. The loop will continue executing as long as bothx
andy
are greater than 0. - Loop Body: Inside the loop, we print the current values of
x
andy
and then decrement both variables (x--
andy--
). - Loop Exit: The loop will break when either
x
ory
becomes non-positive. In other words, as soon as one of the variables reaches 0 or goes below 0, the loop will exit.
The output is:
x: 5, y: 3
x: 4, y: 2
x: 3, y: 1
Loop exited. x: 2, y: 0
2. The do-while Statement
The do-while
loop stands out as a unique construct that ensures the execution of a block of code at least once. Unlike the while
loop, which may not run at all if the initial condition is not met, the do-while
loop guarantees the execution of its body before checking the loop condition.
The do-while
loop has a distinctive structure that separates it from other loops in Java. The key components include:
do {
// Code to be executed
} while (booleanExpression);
do
Keyword: Initiates thedo-while
loop, indicating the beginning of the loop body.- Loop Body: The block of code encapsulated within curly braces
{}
. This code is executed at least once, regardless of the initial state of the boolean expression. while
Keyword: Marks the continuation of the loop structure and introduces the loop condition.- Boolean Expression: A condition that determines whether the loop should continue. If the boolean expression evaluates to
true
, the loop will repeat. If it evaluates tofalse
, the loop terminates.
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
}
}
- The loop body is executed for the first time, printing “Number: 1” and incrementing
i
to 2. - The boolean expression (
i <= 5
) is evaluated. Sincei
is 2, the condition istrue
. - The loop body is executed again, printing “Number: 2” and incrementing
i
to 3. - Steps 2-3 are repeated until
i
becomes 6. - When
i
is 6, the boolean expression becomesfalse
, and the loop terminates.
the output is:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. Comparing while and do-while loops
In Java, the choice between using a while
loop and a do-while
loop depends on the specific requirements of the situation. Generally, the recommendation is to use a while
loop when the code may execute zero or more times, and a do-while
loop when the code needs to execute one or more times. Let’s delve into the distinctions between these loops and provide examples to showcase their applications.
public class WhileVsDoWhileExample {
public static void main(String[] args) {
int counter1 = 0;
System.out.println("Using while loop:");
while (counter1 < 0) {
System.out.println("While loop execution: " + counter1);
counter1++;
}
int counter2 = 0;
System.out.println("\nUsing do-while loop:");
do {
System.out.println("Do-while loop execution: " + counter2);
counter2++;
} while (counter2 < 0);
}
}
This example demonstrates that the while
loop may not execute at all, while the do-while
loop ensures at least one execution of the loop body.
4. Infinite Loops
While while
loops are powerful constructs for repeating tasks, they come with a caveat: the potential for creating infinite loops. An infinite loop is a loop that continues to execute indefinitely, posing numerous problems including overflow exceptions, memory leaks, performance issues, resource exhaustion, and application crashes.
public class InfiniteLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("This loop will never end!");
// No increment or update to i, leading to an infinite loop
}
}
}
In this example, the loop has no mechanism to increment or update the value of i
, causing it to stay less than 5 indefinitely. The loop condition (i < 5
) is always true
, leading to an infinite loop.
Mitigating the risks:
Whenever you write a while
loop, it’s crucial to examine the termination condition to ensure it will eventually be met under some conditions. Here are a few tips:
- Update Variables: Ensure that the loop variable or variables are updated within the loop body so that the condition becomes false at some point. In other words, make sure the loop condition, or the variables the condition is dependent on, are changing between executions.
- Break Statements: Introduce
break
statements or other mechanisms to exit the loop when a certain condition is met. - Logical Termination: Choose termination conditions that logically make sense for your application.
To fix the infinite loop in the previous example, we can increment the loop variable i
within the loop body:
public class FixedInfiniteLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("This loop will eventually end!");
i++; // Increment i to ensure the loop terminates
}
}
}