for loop in java

(Last Updated On: February 25, 2019)

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:

 

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)

 

 

Infinite for loop

Below syntax run a for loop for infinite time.

Code example:

 

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.

 

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.

 

 

For each loop in Java

Simplified version of for loop. Good use with collection.

Java code: