For & While Loops
Loops let you repeat a block of code multiple times. Java has three types of loops: 'for' (when you know how many times), 'while' (when you have a condition), and 'do-while' (runs at least once). This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
45 min•By Priygop Team•Last updated: Feb 2026
Loop Types in Java
Example
public class LoopDemo {
public static void main(String[] args) {
// FOR LOOP — when you know the count
System.out.println("=== For Loop ===");
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// WHILE LOOP — when you have a condition
System.out.println("\n=== While Loop ===");
int countdown = 5;
while (countdown > 0) {
System.out.println("T-minus " + countdown);
countdown--;
}
System.out.println("Liftoff!");
// DO-WHILE LOOP — runs at least once
System.out.println("\n=== Do-While Loop ===");
int num = 1;
do {
System.out.println("Number: " + num);
num *= 2;
} while (num <= 20);
// ENHANCED FOR LOOP (for-each)
System.out.println("\n=== Enhanced For Loop ===");
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
// Nested loops (multiplication table)
System.out.println("\n=== 5x5 Multiplication Table ===");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}Try It Yourself: Number Patterns
Try It Yourself: Number PatternsJava
Java Editor
✓ ValidTab = 2 spaces
Java|40 lines|1150 chars|✓ Valid syntax
UTF-8