With the help of for loop, a block of code can be executed a fixed number of times.
Syntax
for(initialization; condition; increment/decrement) { //code to be executed }
for loop has three different statement separated by a semicolon, and are explained below-
Flowchart of for loop
public class Example { public static void main(String args[]) { for(int i=1; i<=10; i++) { System.out.println(2*i); } } }
Output
2 4 6 8 10 12 14 16 18 20
It is also called enhanced for loop. For-Each loop enables a programmer to iterate through an array or a collection easily.
Syntax to iterate through array
for(type variable : arrayName) { //code to be executed }
Syntax to iterate through collection
for(type variable : collectionName) { //code to be executed }
class Test { public static void main(String args[]) { int arr[] = {2,4,6,8,10}; for(int i : arr) { System.out.println(i); } } }
Output
2 4 6 8 10
import java.util.ArrayList; class Test { public static void main(String args[]) { ArrayListlang = new ArrayList (); lang.add("Java"); lang.add("Python"); lang.add("MongoDB"); for(String i : lang) { System.out.println(i); } } }
Output
Java Python MongoDB
If you write nothing in the initialization statement, condition, and increment/decrement part then it will be infinite for loop.
Syntax
for(;;) { //code to executed }
Example
public class Example { public static void main(String args[]) { for(;;) { System.out.println("This is infinite loop."); } } }
Output
This is infinite loop. This is infinite loop. This is infinite loop. This is infinite loop. ctrl+c
Press ctrl+c to exit infinite loop.