Java For Loop Example
Java For Loop Example describes about how to use for loop in java.
The general template of for statement is following
for (initialization; termination; increment){ statement(s) }
When you use "for loop" you need to follow below rules
The initialization condition initializes the loop; it is executed only once, as the loop begins. if the termination condition tests to false, the loop exits. The increment condition is invoked after each iteration through the loop;
The following are the different ways we can use for loop in java
1) For loop Example
public class ForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i);
}
}
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i);
}
}
}
Output
1 2 3 4 5
2) For loop With Comma
public class ForLoop {
public static void main(String[] args) {
for (int i = 1, j = 0; i < 10; i = i + 1) {
System.out.println(i + j);
}
}
}
public static void main(String[] args) {
for (int i = 1, j = 0; i < 10; i = i + 1) {
System.out.println(i + j);
}
}
}
Output
1 2 3 4 5 6 7 8 9
3) Iterate Array Using For Loop
public class ForLoop {
public static void main(String[] args) {
for (String str : new String[] { "java", "jsp" }) {
System.out.println(str);
}
}
}
public static void main(String[] args) {
for (String str : new String[] { "java", "jsp" }) {
System.out.println(str);
}
}
}
Output
java
jsp
4) Infinite For Loop
public class ForLoop {
public static void main(String[] args) {
for (;;) { // infinite loop
System.out.print("hello");
}
}
}
public static void main(String[] args) {
for (;;) { // infinite loop
System.out.print("hello");
}
}
}
Output
hello hello ........ ........