Loops in Java
Introduction
In Java, code execution generally follows a sequential flow, with each block executing once. However, there are scenarios where we need to repeat a particular block multiple times. Instead of rewriting the same code, we use loops, which allow us to execute a block of code multiple times efficiently.
Java provides three types of loops:
- while loop
- do-while loop
- for loop
1. While Loop
The while
loop in Java continuously executes a block of code as long as the given condition remains true. It is similar to Python's while
loop, but Java uses curly braces {}
instead of indentation.
Syntax:
while (condition) {
// loop body
}
class Main {
public static void main(String[] args) {
int num = 4;
int counter = 0;
while (counter < 3) {
num++;
System.out.println(num);
counter++;
}
}
}
Output:
6
7
num
and printing its value.Common Mistakes in While Loop:
Incorrect Termination Condition :
Error: Infinite loop because the condition
variable does not update within the loop.
Not Updating Counter Variable :
class Main {
public static void main(String[] args) {
int n = 4;
int counter = 0;
while (counter < 3) {
n++;
System.out.println(n);
}
}
}
counter
variable is not incremented, causing the condition to always remain true.2. Do-While Loop
The do-while
loop is similar to while
, but it executes at least once before checking the condition.
Syntax :
do {
// loop body
} while (condition);
Example :
Output:
Key Difference from While Loop:
Even if the condition is false, the loop body executes at least once.
Example:
class Main {
public static void main(String[] args) {
int n = 3;
boolean condition = (n > 10);
do {
System.out.println("Number is greater than 10");
} while (condition);
}
}
Output:
n > 10
is false, the message prints once before exiting.3. For Loop
The for
loop is widely used when the number of iterations is known in advance. It consists of three parts:
- Initialization: Declares and initializes the loop variable.
- Condition: Checks whether the loop should continue.
- Update Expression: Modifies the loop variable after each iteration.
Syntax:
Example:
Output:
Common Mistakes in For Loop:
Incorrect Syntax (Missing Semicolons) :
Summary
- In while and for loops, the condition is checked before executing the loop body.
- In do-while, the condition is checked after executing the loop body at least once.
- The for loop is preferred when the number of iterations is known, while while and do-while loops are useful for indefinite loops with dynamic conditions.