For loop in Java

 

For loop in Java


1. For loop

 Syntax

for (initialization; termination; increment) {
    statement(s)
}
  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

 Flow of the for loop


First step:
 In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.


Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.


Fourth step: After the third step, the control jumps to the second step and the condition is re-evaluated.

Example for Loop

public class ForLoopExample {
    public static void main(String args[]) {
        // here, n is declared inside of the for loop
        for (int n = 10; n > 0; n--)
            System.out.println("tick " + n);
    }
}
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Note that we have declared a loop control variable inside the a for loop. When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does.
When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i , is declared inside the for since it is not needed elsewhere.
public class ForLoopFindPrime {
    public static void main(String args[]) {
        int num;
        boolean isPrime;
        num = 14;
        if (num < 2)
            isPrime = false;
        else
            isPrime = true;
        for (int i = 2; i <= num / i; i++) {
            if ((num % i) == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime)
            System.out.println("Prime");
        else
            System.out.println("Not Prime");
    }
}
Output:
Not Prime

2. For-Each

Beginning with JDK 5, the second form of for was defined that implements a “for-each” style loop. Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.

Syntax

for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end.
Here is an entire program that demonstrates the for-each version:
public class ForEachExample {
    public static void main(String args[]) {
        int nums[] = {
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10
        };
        int sum = 0;
        // use for-each style for to display and sum the values
        for (int x: nums) {
            System.out.println("Value is: " + x);
            sum += x;
        }
        System.out.println("Summation: " + sum);
    }
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

The for-each Loop is Essentially Read-Only

There is one important point to understand about the for-each style loop. Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying array. In other words, we can’t change the contents of the array by assigning the iteration variable a new value.
For example, consider this program:
package net.javaguides.corejava.controlstatements.loops;

public class ForEachNoChange {
    public static void main(String args[]) {
        int nums[] = {
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10
        };
        for (int x: nums) {
            System.out.print(x + " ");
            x = x * 10; // no effect on nums
        }
        System.out.println();
        for (int x: nums)
            System.out.print(x + " ");
        System.out.println();
    }
}
Note that the first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect on the underlying array nums, as the second for loop illustrates.

The for-each Loop - Iterating Over Multidimensional Arrays

The enhanced version of the for also works on multidimensional arrays. The following program uses the for-each style for a two-dimensional array:
package net.javaguides.corejava.controlstatements.loops;

public class ForEachMultidimensionalArrays {
    public static void main(String args[]) {
        int sum = 0;
        int nums[][] = new int[3][5];
        // give nums some values
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 5; j++)
                nums[i][j] = (i + 1) * (j + 1);
        // use for-each for to display and sum the values
        for (int x[]: nums) {
            for (int y: x) {
                System.out.println("Value is: " + y);
                sum += y;
            }
        }
        System.out.println("Summation: " + sum);
    }
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90

Search an Array Using for-each Style Example

The following program uses a for each loop to search an unsorted array for a value. It stops if the value is found.
package net.javaguides.corejava.controlstatements.loops;

public class ForEachSearchArray {
    public static void main(String args[]) {
        int nums[] = {
            6,
            8,
            3,
            7,
            5,
            6,
            1,
            4
        };
        int val = 5;
        boolean found = false;
        // use for-each style for to search nums for val
        for (int x: nums) {
            if (x == val) {
                found = true;
                break;
            }
        }
        if (found)
            System.out.println("Have found value");
    }
}
Output:
Have found value
The for-each style for is an excellent choice in this application because searching an unsorted array involves examining each element in a sequence.