Java: For and Enhanced For Loop

At this point, let us look closely at looping statements in Java. The most commonly used looping statements in Java include the ‘for statement’, the ‘enhanced for statement,’ the ‘while statement,’ and the ‘do-while statement.’

For Statement

When programmers use the ‘for statement,’ a particular block of statements is executed repeatedly until the test condition becomes invalid.  

The syntax for a for statement is:

for (initial value; test condition; modification to value) {
    // Do Some Task
}

Let us look at a very simple example to see how the for statement works.

import java.util.Scanner;
	
public class ExampleFor { 
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 5; i++) {
			System.out.println(i); 
        }
    }
}

It is important to direct all the focus towards the first line:

for (int i = 0; i < 5; i++)

See that three different parts are present, each of them separated by a semi-colon.

The first part is a simple declaration and assignment statement, wherein a variable i (int type) is assigned to zero. This variable also works as a loop counter.

The second part is a condition that evaluates if i is smaller than 5. In this case, the statements following the for statement that are enclosed within the curly brackets are executed. Since there is only one statement enclosed within the brackets, the brackets are optional.   

Upon the System’s execution of System.out.println(i) statement, the compiler goes back to the for statement’s last part. i++ increments the value of i by 1 unit, making its value 1. 

Then again, i is tested if it is smaller than 5. 

The System.out.println(i) statement is printed again if it is less than 5.

This loop goes on until the value of i is no longer less than 5. When that happens, the ‘for statement’ is exited, and the rest of the program is executed.  

For our example, the output will be:

0
1
2
3
4

The output does not go beyond 4 as the System.out.println(i) method is not executed after i becomes 5, as 5 is not less than 5.  

Usually, the for statement is extremely useful to loop through an array. For instance, if 

int[] exampleNumbers = {30, 60, 90, 120, 150};

the for statement and the length field of the array can help loop through the array as shown below.

public class ForLength { 
    public static void main(String[] args) { 
        int[] exampleNumbers = {30, 60, 90, 120, 150};

        for (int i = 0; i < exampleNumbers.length; i++) {
            System.out.println(exampleNumbers[i]);
        }
    }
}

Since exampleNumbers.length will return 5, this code will be executed until i becomes equal to 4. Running the program will print the following output:

30
60
90
120
150

Enhanced For Statement

An enhanced for statement can also be used when working with arrays and Collections. An enhanced for statement is especially useful when scanning through information from an array, without altering the data.

The syntax for an enhanced for statement is:

for (variable declaration : name of array) {
    // Body of enhanced for loop
}

For instance, in this example

int[] exampleNumbers = {30, 60, 90, 120, 150};

Use the following code to display the elements of the array.

for (int abc : exampleNumbers)
    System.out.println(abc);

In the example above, an int variable called abc has been declared and used for looping. With every running of the loop, an element from the exampleNumbers array is assigned to the variable abc. That is, the first time the loop is executed, 30 is assigned to abc.

The line System.out.println(abc); is used to display the output as 30. 

When the loop is executed the second time, the integer 60 is assigned to abc. The line

System.out.println(abc);

Displays 60.

This loop goes on until the five elements present within an array are displayed.  

Leave a Reply

%d bloggers like this: