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:
1 2 3 4 5 |
for(int i = 0; i < 5; i++) { System.out.println(“Number”+i); } |
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:
1 2 3 4 5 |
for(;;) { //statements } |
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:
1 2 3 4 5 6 7 |
int arr[] = {1,2,3,4,5} for(int element:arr) { System.out.println(“Element of array:”+element); } |
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.