Java – For Loop

checkout SourceCode here

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.

There are three types of for loop in java.

  • Simple For Loop
  • For-each or Enhanced For Loop

Java Simple For Loop

The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.

Syntax:

  1. for(initialization;condition;incr/decr){
  2. //code to be executed
  3. }

for loop in java flowchart

Example:

public class ForExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
5
6
7
8
9
10

 

Java For-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

  1. for(Type var:array){
  2. //code to be executed
  3. }

Example:

public class ForEachExample {
    public static void main(String[] args) {
        int arr[] = {12, 23, 44, 56, 78};
        for (int i : arr) {
            System.out.println(i);
        }
    }
}

Output:

12
23
44
56
78

Java Infinitive For Loop

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

  1. for(;;){
  2. //code to be executed
  3. }

Example:

public class InfinitiveForLoop {
    public static void main(String[] args) {
        for (; ; ) {
            System.out.println("infinitive loop");
        }
    }
}

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Leave a Reply

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