Looping is a fundamental concept in programming that allows us to execute a block of code repeatedly until a specific condition is met. In Java, there are various looping constructs that serve different purposes. This article explores the different types of loops, how to use them, and dive into practical examples to demonstrate their usage.
Types of Loops in Java
The For Loop
A basic loop that executes a block of code for a fixed number of times. The for loop is commonly used when we know in advance how many times we want to execute a particular block of code. It consists of three parts: initialization, condition, and increment (or decrement). The syntax of the for loop is as follows:
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
Let’s use a for loop to print the numbers from 1 to 10:
public class ForLoop {
public static void main(String[] args) {
// Output: 1 2 3 4 5 6 7 8 9 10
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
}
}
We have a for loop that is responsible for the repetition. The loop initializes the loop variable i with an initial value of 1. The loop continues as long as the condition i <= 10 is true. After each iteration, the loop variable i is incremented by 1 using the i++ statement.
Inside the loop, we have the statement System.out.print(i + ” “), which prints the value of i followed by a space. The print method is used instead of println to keep the numbers on the same line. As a result, the loop executes 10 times, printing the numbers from 1 to 10 separated by spaces.
The While Loop
A loop that repeatedly executes a block of code as long as a specified condition is true. The while loop is useful when the number of iterations is not known in advance, and we want to repeat the code block as long as a condition is true. The syntax of the while loop is as follows:
while (condition) {
// Code to be executed repeatedly
}
Let’s use a while loop to print a countdown from 10 to 1:
public class WhileLoop {
public static void main(String[] args) {
int count = 10;
// Output: 10 9 8 7 6 5 4 3 2 1
while (count >= 1) {
System.out.print(count + " ");
// Decrement count
count--;
}
}
}
We have a while loop that starts with an initial value of count set to 10. The loop will continue as long as the condition count >= 1 is true.
Inside the loop, the current value of count is printed using System.out.print(count + ” “), followed by a space. Then, the value of count is decremented by 1 using the statement count–. This ensures that the loop progresses towards the termination condition.
The Do-While Loop
Similar to the while loop, but it guarantees at least one execution of the loop body before checking the condition. The do-while loop is similar to the while loop, but the difference is that the condition is checked after the code block execution. This guarantees that the loop body will execute at least once, irrespective of the condition. The syntax of the do-while loop is as follows:
do {
// Code to be executed repeatedly
} while (condition);
Let’s use a do-while loop to repeatedly prompt the user to enter “q” in order to exit the program. This is a perfect example of a do-while loop because the test is conducted after at least one execution of the code block. We want to ensure that we receive input from the user before testing it with our exit key.
import java.util.Scanner;
public class DoWhileLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String exitKey;
do {
System.out.print("Enter 'q' to exit program: ");
exitKey = input.nextLine();
} while (!exitKey.equalsIgnoreCase("q"));
System.out.println("Exiting Program...");
}
}
We have a do-while loop that executes the code block at least once and repeats as long as the condition !exitKey.equalsIgnoreCase(“q”) is true. This condition checks if the user’s input, stored in the exitKey variable, is not equal to “q” (case-insensitive).
Inside the loop, the program prompts the user to enter ‘q’ to exit using System.out.print(“Enter ‘q’ to exit program: “). The user’s input is read and stored in the exitKey variable using exitKey = input.nextLine().
After each iteration, the loop condition is evaluated. If the user enters “q” (case-insensitive), the condition becomes false, and the loop exits. Otherwise, the loop continues, prompting the user again.
Once the loop finishes, the program prints “Exiting Program…” using System.out.println() to indicate that the loop has been exited.
The For-Each Loop (Enhanced For Loop)
A loop used specifically for iterating over elements in arrays or collections. The for-each loop, also known as the enhanced for loop, is specifically designed for iterating over elements in arrays or collections. It simplifies the code required to iterate over these structures. The syntax of the for-each loop is as follows:
for (elementType element : array/collection) {
// Code to be executed repeatedly
}
Let’s use a for-each loop to calculate the sum of elements in an array:
public class ForEachLoop {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int number : numbers) {
sum += number;
}
// Output: 55
System.out.println(sum);
}
}
We have an array numbers containing integer values from 1 to 10. We want to calculate the sum of these numbers.
The for-each loop iterates over each element in the numbers array. For each iteration, the current element is assigned to the variable number, and the code block within the loop is executed. In this case, the code block simply adds the current number to the sum variable using sum += number.
After the loop finishes executing for all elements in the array, the sum variable contains the sum of all numbers. Finally, the sum is printed using System.out.println(sum).
Loop Control Statements: Break and Continue
Java provides two loop control statements: break and continue. These statements allow us to alter the flow of execution within a loop.
The break Statement
The break statement is used to terminate the current loop and resume execution at the next statement following the loop. It is often used when a specific condition is met, and we want to exit the loop early. Let’s see an example where we exit the loop when the variable i is equal to 5:
public class BreakStatement {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
// Exit loop
break;
}
// Output: 1 2 3 4
System.out.print(i + " ");
}
System.out.printf("%nOut of the loop!");
}
}
We have a for loop that iterates from 1 to 10 using the loop variable i. For each iteration, the code block within the loop is executed.
Inside the loop, there is an if statement that checks if the current value of i is equal to 5 using the condition i == 5. If the condition evaluates to true, the break statement is encountered, which immediately exits the loop.
Therefore, when i reaches 5, the loop is terminated, and the program proceeds to the statement following the loop. In this case, it prints “Out of the loop!” using System.out.printf(“%nOut of the loop!”).
The continue Statement
The continue statement is used to skip the current iteration of the loop and move to the next iteration. It is often employed when we want to exclude specific elements from processing within the loop. Let’s take a look at an example code where we skip all even numbers from 0 to 50:
public class ContinueStatement {
public static void main(String[] args) {
for (int i = 0; i <= 50; i++) {
if (i % 2 == 0) {
// Go to next iteration
continue;
}
// Output: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
System.out.print(i + " ");
}
}
}
we have a for loop that iterates from 0 to 50. Inside the loop, we check if the current number i is even by using the condition i % 2 == 0. If it is even, we encounter the continue statement, which skips the remaining code in the current iteration and proceeds to the next iteration. Therefore, even numbers are excluded from being printed, resulting in only odd numbers being displayed in the output.
Conclusion
This article explored the different types of loops in Java and learned how to effectively use them in our programs. We covered the for loop, while loop, do-while loop, and for-each loop, along with practical examples for each. Additionally, we discussed the loop control statements break and continue to alter the flow of execution within loops. By mastering looping constructs, you can write efficient and flexible programs that can handle repetitive tasks effectively.
Related Links
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!