Loops in Java
What are Loops in Java
Loops are used to execute a block of code repeatedly until a specified condition is met. They help reduce code repetition and improve efficiency.
google.com, pub-8434817042454839, DIRECT, f08c47fec0942fa0
for Loop
Used when the number of iterations is known.
for(int i = 1; i <= 5; i++){
System.out.println(i);
}
System.out.println(i);
}
while Loop
Used when the number of iterations is not fixed.
int i = 1;
while(i <= 5){
System.out.println(i);
i++;
}
while(i <= 5){
System.out.println(i);
i++;
}
do-while Loop
Executes the code at least once before checking the condition.
int i = 1;
do{
System.out.println(i);
i++;
} while(i <= 5);
do{
System.out.println(i);
i++;
} while(i <= 5);
Differences Between Loops
- for loop: best when iterations are known
- while loop: best for condition-based execution
- do-while loop: executes at least once

