Loops in Java
Loops in Java are used to execute a block of code repeatedly until a specific condition is met. Java supports several types of loops:
1. while Loop
The while loop executes a block of code as long as a specified condition is true.
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count is: " + i);
i++;
}
}
}
2. do-while Loop
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition.
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count is: " + i);
i++;
} while (i <= 5);
}
}
3. for Loop
The for loop is used when you know exactly how many times you want to execute a block of code.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
}
}
4. for-each Loop
The for-each loop is used to iterate through elements of an array or a collection.
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("Number is: " + number);
}
}
}
Loop Control Statements
Java provides loop control statements break and continue to control the execution flow of loops:
break Statement
The break statement terminates the loop and transfers control to the next statement outside the loop.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println("Count is: " + i);
}
}
}
continue Statement
The continue statement skips the current iteration of the loop and proceeds to the next iteration.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Count is: " + i);
}
}
}