Java For loop is used to repeatedly execute a particular program code several times.The number of iteration must be fixed. 3 Type of Java ...
Java For loop is used to repeatedly execute a particular program code several times.The number of iteration must be fixed.
3 Type of Java For Loop
- Simple for loop
- For -each or Enhanced for loop
- Labeled for loop
Simple Java For Loop
Java for loop is just same as C/C++.
Syntax:
[for(initialization;condition;increment/decrement){
// execute this code
}]
Example:
[
public class JavaForLoop { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here for(int i=0;i<=10;i++) { System.out.println("The number is "+i); } } }
]
Java For -each or Enhanced for loop
Java for-each loop is mainly used to iterate through arrays or other Java collections.It works with the used of an index and its able to return values.
Syntax:
[
for(Type variable:array){ //code to be executed }
]
Example:
[
public class ForeachLoop { public static void main(String args[]) { int score[]={22,11,33,44,55};//initialize array for(int s:score) { System.out.println("Score is "+s); } } }
]
Java Labeled for loop
As the name suggests, each for loop has name, i.e., labeled. Using break keyword, we are able to break away from the inner loop and continue with outer loop.
Syntax:
[label:
for(initialization;condition;increment/decrement){ //code to be executed
} ]
Example:
[
public class LabeledForLoop { public static void main(String args[]) { kk: for(int i=1;i<=3;i++){ dd: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break dd; } System.out.println(i+" "+j); } } } }
]
Java infinitive loop
Adding two semicolons in the condition part creates infinitive loop.
Example:
Run below code
[
public class InfinitiveLoop { public static void main(String args[]) { for(;;) { System.out.println("Infinitive loop Example"); } } }
]