for Loops

Learn how to iterate with a for loop.

Java for loop

There are three parts in a for loop header:

  1. Initialization
  2. Boolean expression
  3. Increment or decrement

In a while loop, initialization is done before writing the header of the loop. The boolean expression is specified next to the while keyword, and incrementing or decrementing is done inside the loop. However, here, all three parts are present in a single line.

Here is its syntax:

for (initialization; bool-expression; increment/decrement)
{
   statement(s)   // statements to be executed
}

These three parts are to be separated by ; (semicolon). Here are some key points:

  • The initialization statement is executed only one time before the execution of the code block. The variable being initialized is referred to as a loop control variable.

  • The bool-expression defines the condition for executing the code block.

  • The increment/decrement statement is executed every time, after the code block has been executed.

Let’s visualize this.

Get hands-on with 1400+ tech skills courses.