Learn about the different types of loops in Java, when to use each type, and how to write efficient loop structures.
A while loop executes a block of code as long as its condition remains true.
// Example: Counting from 1 to 5 using a while loop
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++;
}
A for loop provides a compact way to iterate over a range of values with initialization, condition, and iteration expressions.
// Example: Counting from 1 to 5 using a for loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
Nested loops place one loop inside another, often used for working with multi-dimensional data.
// Example: Printing a simple pattern using nested loops
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Output:
// *
// * *
// * * *
The break statement immediately terminates the loop it's in.
// Example: Using break to exit a loop early
for (int i = 1; i <= 10; i++) {
if (i == 6) {
System.out.println("Breaking the loop at i = " + i);
break;
}
System.out.println("Value of i: " + i);
}
The continue statement skips the current iteration and proceeds to the next one.
// Example: Using continue to skip even numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Odd number: " + i);
}