Java for loop With Examples

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.

  • “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.


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

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.

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.

That’s all about java for loop.

Reference: Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: