x

Java – For loop

PREV     NEXT

Java For loop:


Java – For loop executes a set of statements repeatedly until a specified condition evaluates to false.

Syntax :

Java For loop has 3 parts

  • Initialization – Executes once, initializes the loop variable which causes the loop to iterate
  • Condition – Specifies the expression which evaluates to true / false. When this condition becomes false, the loop is terminated.
  • increment/decrement – Exceutes at every iteration of the loop, causes the loop variable either to increment or decrement.
for (initialization; condition; increment/decrement)

{

//statements to be repeated

}

Example:

Output:

Number:0


Number:1

Number:2

Number:3

Number:4

Note: The 3 parts of the ‘for’ loop can be made optional if necessary. Without them, it becomes an infinite loop

Example:

Enhanced Java – For loop:

Enhanced for loop is the simpler form of the usual ‘for’ loop, usually used to iterate over an array or collection object.

Example:

Output:

Element of array:1

Element of array:2

Element of array:3

Element of array:4

Element of array:5

Here, each value of ‘arr’ is assigned to ‘element’ as it iterates over the loop from the index 0.

PREV     NEXT



Like it? Please Spread the word!