For Loop in Java


There are two forms of the for loop. The first is the thematic form which is effective from the original version of Java. The second is the newer "for-each" form, added by JDK 5. Here is the general form of the traditional for statement :

for(initialization; condition; iteration)
{
  //body of code
}

For Loop Example 1

In the example below, the initialization for loop is int i = 0, the condition is i <10 and the iteration is i++.

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

For Loop Example 2

The following example shows the odd numbers between 1-100 with the help of for loop.

Program
public class Main
{
	public static void main(String[] args) 
	{
		// print odd number between 1-100
		for(int i=1;i<100;i+=2)
		{
		    System.out.println(i);
		}
	}
}
Run

Nested For Loop

Like all other programming languages, Java allows for loops to be nested. That is, one loop may be inside another.

Program
public class Main
{
	public static void main(String[] args) 
	{
		// print star pattern
		for(int i=1; i<=5;i++)
		{
		    for(int j=1;j<=i;j++)
		    {
		        System.out.print(" * ");
		    }
		    System.out.println();
		}
	}
}
Run

For Loop Using the Comma

There will be times when you want to include multiple statements in the beginning and repeat sections of the loop, then you have to put a comma (,) in the for loop.

Program
public class Main
{
	public static void main(String[] args) 
	{
	    int a,b=10;
		for(a=1; a<=10&&b>=1;a++,b--)
		{
		    System.out.println(a+" "+b);
		}
	}
}
Run