Java for loop

Filed Under: Java

Java for loop is used to iterate over a range of values. We can use for loop to iterate over an array, a list, java set etc.

Java for loop

There are three types of for loop in java.

  1. General for loop
  2. for-each or enhanced for loop
  3. Java For loop with label

Let’s look into different type of java for loop example.

Java for loop example

General for loop in java have following form.


for (variable initialization; termination condition; increment/decrement operation) {
    // statements to be executed
}
  • “variable initialization” happens only once when for loop begins execution.
  • “termination condition” should result in boolean expression, if it returns false then for loop terminates.
  • “increment/decrement” operation is performed after each for loop execution. In most of the scenarios, it should lead towards the termination condition unless you want for loop to not terminate at all.

Below image shows the flow chart of java for loop.
java for loop

Suppose we want to print integers 5 to 10, in this case we can use basic for loop.


package com.journaldev.javaforloop;

public class JavaForLoop {

	public static void main(String[] args) {
		
		//print integers 5 to 10
		for (int i=5; i<=10; i++) {
			System.out.println("Java for loop example - " + i);
		}
	}

}

java for loop example

Java for each loop

Java for each loop is also called enhanced for loop. We can use for each loop to iterate over array or collection elements. Java for each loop is the recommended way wherever it’s possible to use it. It’s very easy and compact to write.


package com.journaldev.javaforloop;

import java.util.ArrayList;
import java.util.List;

public class JavaForEachLoopExample {

	public static void main(String[] args) {
		int[] intArray = { 1, 2, 3, 4, 5 };

		for (int i : intArray)
			System.out.println("Java for each loop with array - " + i);

		List<String> fruits = new ArrayList<>();
		fruits.add("Apple");
		fruits.add("Banana");
		fruits.add("Orange");

		for (String f : fruits)
			System.out.println("Java for each loop with collection - " + f);
	}

}

java for each loop, enhanced for loop java

Notice from above example is that if there is only one statement in the for loop, then we don’t need to put them inside curly braces {}.

Java for loop with label

We can add a label to for loop, it’s useful with break and continue statements to get out of outer loop. Note that by default break and continue statements work with inner loop only. Here is an example of for loop with label and how it’s used with continue statement.


int[][] intArr = { { 1, -2, 3 }, { 0, 3 }, { 1, 2, 5 }, { 9, 2, 5 } };

process: for (int i = 0; i < intArr.length; i++) {
	boolean allPositive = true;
	for (int j = 0; j < intArr[i].length; j++) {
		if (intArr[i][j] < 0) {
			allPositive = false;
			continue process;
		}
	}
	if (allPositive) {
		// process the array
		System.out.println("Processing " + Arrays.toString(intArr[i]));
	}
	allPositive = true;
}

That’s all about java for loop.

Reference: Oracle Documentation

Comments

  1. Bhawna says:

    Could you please provide the output for the last example for label.

    1. Abhinav says:

      Processing [0, 3]
      Processing [1, 2, 5]
      Processing [9, 2, 5]

  2. Soheil says:

    Hi,
    it seams that in last example, allpossitive=true; in last line is extra;

  3. Shanmuganand Kanniappan says:

    Hi,

    Since we are talking about for loop in details, its good to mention that all three parameters (variable initialization; termination condition; increment/decrement operation) in the for loop are optional. Meaning below is a valid for loop.

    for (;;) {
    //Some stuff
    }

    Above is a infinite for loop allowed in java.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages