Member-only story
Java Loops: For, While, and Do-While
Loops in Java are fundamental control flow statements that allow developers to execute a block of code multiple times, reducing redundancy and improving efficiency. Java provides three main types of loops: for, while, and do-while. Each loop has its use cases, advantages, and potential pitfalls. This article will explore these loops in depth, with examples and best practices.
Not a Medium member? No problem! Read the full article here. Enjoy!
1. For Loop in Java
Definition
A for loop is used when the number of iterations is known beforehand. It consists of three parts:
- Initialization: Declares and initializes the loop control variable.
- Condition: Evaluate whether the loop should continue running.
- Iteration: Updates the loop control variable after each iteration.
Syntax
for(initialization; condition; iteration) {
// Code block to be executed
}Example
public class ForLoopExample {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}








