For loop Program in java
- for
loop is the loop statement in java programming and for loop is used to execute
set of statements until the condition is true.
- for
loop checks the contrition and executes the set of the statements.
- for loop contain the following statements such as “Initialization”, “Condition” and “Increment/Decrement” statement.
For loop Example:
public class ForLoopTest {
public static void main(String a[]){
int i;
for(i=1;i<=5;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
Error free example:
It is an error free but it prints infinite numbers
public static void main(String a[]){
boolean exp = true;
for(int i=1; exp ; i++){
System.out.println(i);
}
}
Compile time error:
It gives compile time error because int exp = true;. Here data type is int value is boolean(true)
public static void main(String a[]){
int exp = true;
for(int i=1; exp ; i++){
System.out.println(i);
}
}
For each loop:
For-each loop introduced in java5 version, it is an advanced of for loop and it is more reliable.
public class ForeachLoop {
public static void main(String args[]){
int a[]={10,20,30,40};
for(int i:a){
System.out.println(i);
}
}
}
Output:
10
20
30
40