For and While Loops
Loops repeat a block of code multiple times until a condition is met.
Example
// For loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// While loop
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
// Do-while loop (runs at least once)
int num = 1;
do {
System.out.println(num);
num++;
} while (num <= 5); Enhanced For Loop and Control
The enhanced for loop iterates over arrays and collections. Use break and continue to control loop flow.
Example
// Enhanced for loop (for-each)
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// break — exit the loop
for (int i = 0; i < 10; i++) {
if (i == 5) break;
System.out.println(i); // prints 0-4
}
// continue — skip to next iteration
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
System.out.println(i); // prints odd numbers
} 