For loop is used to execute a statement or a set of statements repeatedly until a certain condition is met.
for(initialization ; condition ; logic for condition){ // statement(s); }
First Step: The initialization part of the loop happens first and only executes once.
Second Step: The condition is evaluated on each iteration and if it’s true the statement(s) is executed and if it’s false then the iteration will stop.
Third Step: After every statement execution, the logic for condition is executed which purpose is to make condition meet a limit.
for(int i = 0 ;i < 5 ; i++){ System.out.println("i is "+i); }
Output:
i is 0
i is 1
i is 2
i is 3
i is 4
If the condition never becomes false then it’s an infinite loop. Infinite loop is not an expected behavior is Software.
// infinite loop for(int i = 1 ;i >= 1 ; i++){ System.out.println("i is "+i); }
for( ; ; ){ // statement(s); }
Using for loop to loop through an array
int[] numbers = {1,2,3,4,5}; for(int i=0;i<numbers.length;i++){ System.out.println("i is "+numbers[i]); }
Output:
i is 1
i is 2
i is 3
i is 4
i is 5
Foreach Loop
int[] numbers = {1,2,3,4,5}; for(int i : numbers){ System.out.println("i is "+i); }
i is 1
i is 2
i is 3
i is 4
i is 5