for loop in java

Learn for loop in java programming with program examples and explanation with special notes. Demonstration of infinite loop and for each loop with java code are included.

Topics

  • two formats syntax of for loop with example
  • Infinite for loop
  • Special note – semi colon after for ();{}
  • for each loop

Syntax of for loop in java
for(initialization; Boolean_expression; update/ increment/ decrements part)
{
//Statements
}

Code example:

public class Sample {

	public static void main(String[] args) {

		int n = 0;

		for (n = 1; n <= 10; ++n) {
			
			System.out.println(n);
		}

	}
}

 

ANOTHER FOR LOOP FORMAT

Above code can also be written as below. notice that increment of variable in happening in body of the for loop in inside bracket e.g. for (n = 1; n <= 10; // missing)

public class Sample {

	public static void main(String[] args) {

		int n = 0;

		for (n = 1; n <= 10;) {
			
			System.out.println(n);
++n;
		}

	}
}

 

 

Infinite for loop

Below syntax run a for loop for infinite time.

for (  ;  ;  )
{
}

Code example:

public class Sample {

	public static void main(String[] args) {
		
		for (; ;)
		{			
			System.out.println("I am running infinitely...");	
		
		}

	}
}

 

SPECIAL NOTE

Be careful with semi column [; ] after for () bracket before body. for example, for (n = 1; n <= 10; ++n);

Below code will execute for 10 times but will not go inside loop body.

public class Sample {

	public static void main(String[] args) {

		int n = 0;

		for (n = 1; n <= 10;++n);
		{			
			System.out.println(n);	
		
		}

	}
}

 

Below scenario Leads to hang if we use semicolon as for (n = 1; n <= 10;);{}.
In this scenario, increment is not written in for(), but in body.

public class Sample {

	public static void main(String[] args) {

		int n = 0;

		for (n = 1; n <= 10;);
		{
			
			System.out.println(n);			
	
			++n;
		}

	}
}

 

 

For each loop in Java

Simplified version of for loop. Good use with collection.

Java code:

public class Sample {

	public static void main(String[] args) {

		String[] student = { "Peter", "John", "Lisa" };

		for (String name : student) {

			System.out.println(name);
		}

	}
}


Leave a Comment