for loop in Java

With the help of for loop, a block of code can be executed a fixed number of times.

Syntax

for(initialization; condition; increment/decrement)
{
	//code to be executed
}

for loop has three different statement separated by a semicolon, and are explained below-

  • Initialization Statement- It is executed only once. In this, you can declare and initialization variables of the same. The scope the variables declared in the initialization block is limited to the for block.
  • Condition- For each iteration, the condition is evaluated, and if it gives true then the statements define within the for block are executed.
  • Increment/decrement- This block is used to manipulate the value of the variable.

Flowchart of for loop

for loop in Java

Example of for loop

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

Output

2
4
6
8
10
12
14
16
18
20

for-each loop in Java

It is also called enhanced for loop. For-Each loop enables a programmer to iterate through an array or a collection easily.

Syntax to iterate through array

for(type variable : arrayName)
{
	//code to be executed
}

Syntax to iterate through collection

for(type variable : collectionName)
{
	//code to be executed
}

Example of for-each loop to iterate through array

class Test
{
	public static void main(String args[])
	{
		int arr[] = {2,4,6,8,10};
		for(int i : arr)
		{
			System.out.println(i);
		}
	}
}

Output

2
4
6
8
10

Example of for-each loop to iterate through collection

import java.util.ArrayList;
class Test
{
	public static void main(String args[])
	{
		ArrayList lang = new ArrayList();
		lang.add("Java");
		lang.add("Python");
		lang.add("MongoDB");
		for(String i : lang)
		{
			System.out.println(i);
		}
	}
}	

Output

Java
Python
MongoDB

Infinite loop in Java

If you write nothing in the initialization statement, condition, and increment/decrement part then it will be infinite for loop.

Syntax

for(;;)
{
	//code to executed
}

Example

public class Example
{
	public static void main(String args[])
	{
		for(;;)
		{
			System.out.println("This is infinite loop.");
		}
	}
}

Output

This is infinite loop.
This is infinite loop.
This is infinite loop.
This is infinite loop.
ctrl+c

Press ctrl+c to exit infinite loop.