For loop in Java

For Loop is used to execute block of code or instructions repeatedly. For loop executes until the specified condition is true. For loop is a simple form of looping structure in java.

Syntax

for(initialization ; condition ; increment / decrement statement) {
  // block of code to execute multiple times
}


For loop in Java

package com.yawintutor;

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

Output

0
1
2
3
4
5
6
7
8
9


Nested for loop in Java

A for loop is used inside another for loop is called nested for loop. Nested for loops are commonly used to iterate two-dimensional data.

If outer for loop is configured to run n times, inner for loop is configured to run m times, then the code within inner for loop runs n x m times.

package com.yawintutor;

public class NestedForLoop {
	public static void main(String[] args) {
		for (int i = 1; i <= 3; i++) {
			System.out.println("\nSTART OUTER FOR i = " + i);
			for (int j = 1; j <= 3; j++) {
				System.out.println("i = " + i + " j = " + j);
			}
			System.out.println("END   OUTER FOR i = " + i);
		}
	}
}

Output


START OUTER FOR i = 1
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
END   OUTER FOR i = 1

START OUTER FOR i = 2
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
END   OUTER FOR i = 2

START OUTER FOR i = 3
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3
END   OUTER FOR i = 3


for-each Loop in Java

The for-each loop is a simplified form of for loop. It is used to execute all the elements in a java collection object. for-each loops all the elements in a collection and assigns them to the local variable. for-each does not provide index value. By default, for-each executes repeatedly by size of the collection.

package com.yawintutor;

public class ForEachLoop {
	public static void main(String[] args) {
		int[] number = { 1, 2, 3, 4, 5 };
		for (int i : number) {
			System.out.println(i);
		}
	}
}

Output

1
2
3
4
5


Infinite for loop in Java

The for loop allows to execute the block of code by infinite times. In for loop, initialization, conditions and increment / decrement statements are optional. If we remove all specifying only two semicolons, for loop will run infinite times.

Infinite for loops can be stopped by killing the process. (Cntr + C)

package com.yawintutor;

public class InfiniteForLoop {
	public static void main(String[] args) {
		int i = 0;

		for (;;) {
			System.out.println(i++);
		}
	}
}

Output

0
1
2
3
4
5
6
.
.
.
.
.



Related Articles

Leave a Reply

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