Home » Java For Loop

Java For Loop

Java For Loop

In Java, the loop is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. It’s particularly useful when you know the number of iterations beforehand.

for-loop.png

For loop is an entry-controlled loop as we check the condition first and then evaluate the body of the loop.

Flow Diagram

for-loop-java.png

Syntax

The syntax of a for loop in Java is as follows:

for (initialization; condition; iteration) {
    // Body of the loop
}
Java

Example

public class Main {
  public static void main(String[] args) {
    int maxNum = 5;
    /* loop will run 5 times until test condition becomes false */
    for (int i = 1; i <= maxNum; i++) {
      System.out.println(i);
    }
  }
}
Java

Output

1
2
3
4
5
Java


Variations In For-Loop

Enhanced for Loop (For each loop ) in Java

• The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements.

• The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is known as the for-each loop because it traverses each element of the given collection one by one.

• The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, we do not have the option to skip any element because it does not work on an index basis i.e. we cannot access the index of elements, the loop only returns elements.

java-for-loop.png

The syntax of the enhanced for loop in Java is as follows

for (elementType element : arrayOrCollection) {
    // Body of the loop
}
Java
  • elementType: This is the data type of the elements in the array or collection.
  • element: This is the variable that represents each element in the array or collection during each iteration.
  • arrayOrCollection: This is the array or collection over which you want to iterate.

Here’s an example of using the enhanced for loop with an array:

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
Java

In this example:

  • int is the data type of the elements in the array numbers.
  • num is the variable that represents each element in the array during each iteration.
  • numbers is the array over which we want to iterate.
  • Inside the loop body, num is printed to the console.

This loop will iterate over each element in the numbers array and print its value to the console.

Similarly, you can use the enhanced for loop with collections such as ArrayList, LinkedList, etc. Here’s an example with an ArrayList:

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
for (String fruit : fruits) {
    System.out.println(fruit);
}
Java

Multiple Initialization Expressions

Imagine you have a task where you need to keep track of two different things simultaneously. For example, you want to count the number of apples and oranges in a basket. With the multiple initializations variation, you can declare and initialize separate variables for each item right at the start of the loop. So, instead of just initializing a single variable like in a regular for loop, you can use a comma to separate the initializations of multiple variables. This way, you can conveniently set up and manage different counts or variables within the loop.

Here’s an example

int apples, oranges;
for (apples = 0, oranges = 0; apples < 5 && oranges < 3; apples++, oranges++) {
    // Code to count apples and oranges
}
Java

Multiple Update Expressions

Let’s imagine you are organizing a countdown event where you have two countdown clocks: one showing the countdown from 5 to 1, and the other showing the countdown from 10 to 0. To achieve this, you can use a for loop with multiple update expressions.

Code for the above

for (int i = 1, j = 10; i <= 5; i++, j -= 2) {
    System.out.println("Clock 1: " + i + ", Clock 2: " + j);
}
Java

Output

Clock 1: 5
Clock 2: 10
Clock 1: 4
Clock 2: 8
Clock 1: 3
Clock 2: 6
Clock 1: 2
Clock 2: 4
Clock 1: 1
Clock 2: 2
Java

Optional Expressions

In a for loop, the test expression, initialization expression, and update expression are all optional. This means that you can skip any or all of them based on your specific needs.

Here’s an example that demonstrates each of these expressions being skipped:

for (;;) {
    // Code block to be executed
    System.out.println("Hello, world!");
}
Java

Empty Loop

An empty loop in Java is a loop structure where the loop body is intentionally left empty, but the initialization, test, and update expressions are included. It is often used to create delays or pause execution in programs.

Code example

for (int i = 0; i < 10; i++) {
    // Empty loop body
}
Java

Nested Loops in Java

A nested loop in Java refers to a loop structure where one loop is placed inside another loop. This allows you to perform repetitive tasks within repetitive tasks, creating a multi-dimensional iteration structure. Nested loops are commonly used when working with multi-dimensional arrays, processing nested data structures, or implementing complex algorithms that require iterating over multiple levels of data.

nested-loop-java.png

Here’s an example of a nested loop in Java:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        System.out.println("i: " + i + ", j: " + j);
    }
}
Java

In this example, there’s an outer loop (for loop) that iterates over the values of i from 0 to 2, and within each iteration of the outer loop, there’s an inner loop (for loop) that iterates over the values of j from 0 to 1. This results in a total of 6 iterations, with each combination of i and j being printed to the console.

Output

i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
Java

Conclusion

Loops in Java, including the for loop and its variations, are fundamental constructs that allow for the repetition of code based on certain conditions. The basic for loop is ideal for scenarios where the number of iterations is known beforehand. The enhanced for loop, or for-each loop, offers a simpler way to iterate over arrays and collections, making the code more readable and reducing the chance of errors. The ability to use multiple initialization and update expressions within a single for loop adds flexibility, allowing for more complex iteration patterns. Additionally, the option to omit expressions and create empty loops provides further control over the execution flow. Understanding and utilizing these variations effectively can lead to more efficient and cleaner code in Java applications.

Frequently Asked Questions

Q1. What is a for loop in Java?

Ans: for loop is a control flow statement in Java that allows code to be executed repeatedly based on a given condition. It’s particularly useful when the number of iterations is known before the loop starts.


Q2. How does the enhanced for loop differ from a regular for loop?

Ans: The enhanced for loop (or for-each loop) provides a simpler way to iterate over elements in arrays and collections without the need for a counter or index variable. It’s more readable and less prone to errors compared to the traditional for loop but lacks the ability to iterate in reverse or modify the current collection.


Q3. Can you have multiple initialization and update expressions in a for loop?

Ans: Yes, Java allows multiple initialization and update expressions in a for loop, separated by commas. This feature can be used to control multiple variables within a single loop, enhancing the loop’s flexibility.


Q4. What happens if you omit the condition in a for loop?

Ans: Omitting the condition in a for loop creates an infinite loop, as there is no condition to terminate the loop. It’s essential to have a break statement within the loop body to prevent the loop from running indefinitely.


Q5. Is it possible to use a for loop without any expressions?

Ans: Yes, a for loop can indeed be crafted without any initialization, condition, or update expressions, effectively creating a straightforward yet infinite loop structure. Consequently, these loops necessitate a break statement to halt execution; otherwise, they will persist indefinitely.