Page Content

Tutorials

What is the For Loop in Java? & What is nested for loop?

For Loop in Java

The for loop is a fundamental iteration statement in Java, used to repeatedly execute a block of code a specific number of times. It provides a compact way to iterate over a range of values. Java offers two primary forms of the for statement: the traditional for loop and the enhanced for loop (also known as the for-each loop).

Because of its great versatility, the classic for loop is frequently utilized when you know how many times a task needs to be completed.

The following is how it is expressed in general: for (initialization; termination; increment) { statement(s) }.

Let we dissect its constituent parts:

  1. Initialization: The loop starts by executing this expression once. As a counter, it usually declares and initializes a loop control variable. If a variable is declared in the initialization section, its scope is restricted to the block of the for loop. If the variable is not required outside of the loop, this is frequently used because it can lower mistakes. In this part, you can initialize multiple variables, separated by commas.
  2. Condition (Termination Expression): Before every iteration, this Boolean expression is tested as the condition (termination expression). The statement(s) inside the loop’s body are performed if the expression evaluates to true. Program control moves to the statement right after the for loop if it evaluates to false, ending the loop. In the event that the condition is initially false, the loop body might not run.
  3. Iteration (Increment Expression): This expression is used following each loop iteration. The loop control variable is usually increased or decreased, altering its value for the subsequent iteration. Here, the increment (++) and decrement (--) operators are frequently utilized.

Each of the for loop’s three expressions is optional. If you leave all three sections empty, such as for ( ; ; ) { // your code goes here }, you can build an infinite loop. In a similar vein, a loop cannot have a body if every action takes place inside the for statement.

Here’s an example:

class ForDemo {
    public static void main(String[] args) {
        for (int i = 1; i < 11; i++) {
            System.out.println("Count is: " + i);
        }
    }
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Enhanced Loop (for-each)

Java SE 5 introduced the improved for loop, which offers a concise and clear method of iterating over arrays and collections. It simplifies “start to finish” processes, which need a sequential examination of each component.

Its syntax is

for (type itr-var : collection) { statement(s) }
  1. type: Specifies the data type of the iteration variable, which must be compatible with the elements in the collection.
  2. itr-var: The name of the iteration variable that will sequentially receive each element from the collection.
  3. collection: The array or instance of an Iterable interface (like List, Set, Queue, or Map) to be iterated over.

Every iteration retrieves and stores the subsequent element in the collection in itr-var. The cycle keeps going until every element is acquired. When feasible, this type of loop is advised since it reduces loop size, facilitates reading, and guards against boundary mistakes.

The enhanced for loop’s iteration variable (itr-var) is “read-only” with regard to the underlying array or collection. If a new value is assigned to itr-var inside the loop, the original element in the array or collection will remain unchanged. This indicates that improved for loops are appropriate for reading values and iterating, but not for directly changing the collection’s elements. Modifications require an iterator or a conventional for loop with indexing.

Here’s an example:

class EnhancedForDemo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int item : numbers) {
            System.out.println("Count is: " + item);
        }
    }
}

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Additionally, the extended for loop is compatible with multidimensional arrays. Multidimensional arrays are arrays of arrays in Java. The improved for loop produces an array of N-1 dimensions after each iteration over an N-dimensional array.

Nested Loops

One loop is nested inside another loop in a nested loop. Programming constructs like these are frequently employed to tackle a wide range of issues, especially when dealing with two-dimensional data structures like tables or matrices.

Nestled for loops, for instance, are commonly used to process two-dimensional arrays. The inner loop iterates through columns, while the outside loop iterates through rows.

Here’s an example demonstrating nested loops to find factors of numbers:

class FindFac {
    public static void main(String args[]) {
        for (int i = 2; i <= 100; i++) {
            System.out.print("Factors of " + i + ": ");
            for (int j = 2; j < i; j++)
                if ((i % j) == 0) System.out.print(j + " ");
            System.out.println();
        }
    }
}

Output:

Factors of 2: 
Factors of 3: 
Factors of 4: 2 
Factors of 5: 
Factors of 6: 2 3 
Factors of 7: 
Factors of 8: 2 4 
Factors of 9: 3 
Factors of 10: 2 5

Within nested loops, break and continue statements behave specifically:

  • An unlabeled break statement terminates only the innermost loop in which it is located, transferring control to the statement immediately following that loop.
  • A labeled break statement can be used to terminate an outer loop or any enclosing block that has been given a label.
  • An unlabeled continue statement skips the current iteration of the innermost loop and proceeds to the next iteration of that same loop. For for loops, it jumps to the iteration expression first.
  • A labeled continue statement skips the current iteration of the loop marked with the specified label, proceeding to the next iteration of that outer loop.

For loops’ versatility including their several forms and nesting capabilities makes them essential tools for efficient program control in Java.

Index