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);
   
}
  }
}

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);
   
}
  }
}

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);
   
}
  }
}

4) Infinite For Loop

public class ForLoop {
 
public static void main(String[] args) {
   
for (;;) { // infinite loop
     
System.out.print("hello");
   
}
  }
}





Your email address will not be published. Required fields are marked *