What are Loops in Java?
Loops allow you to execute a block of code repeatedly until a condition is met — saving time and reducing redundancy.
Types of Loops in Java:
1️⃣ for Loop
Used when the number of iterations is known.
for (initialization; condition; update) {
// code to be executed
}
Example: Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
2️⃣ while Loop
Used when the number of iterations is not known, and you loop while the condition is true.
while (condition) {
// code to be executed
}
Example: Print numbers 1 to 5
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
3️⃣ do-while Loop
Similar to while
, but runs at least once, even if the condition is false.
do {
// code to be executed
} while (condition);
Example: Print numbers 1 to 5
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
4️⃣ Enhanced for Loop (for-each)
Used for iterating over arrays or collections.
for (datatype item : array) {
// use item
}
Example: Loop through an array
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
Loop Control Statements
break
: Exit the loop completely
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
continue
: Skip current iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}