Here is a quick example showing you how to use different loop types in Java.
For loop
public class JavaLoops { /** * JavaProgrammingForums.com */ public static void main(String[] args) { // For loop example for(int a = 0; a < 10; a++){ System.out.println("This is a for loop"); } } } Example output:
This is a for loop
This is a for loop
This is a for loop
This is a for loop
This is a for loop
This is a for loop
This is a for loop
This is a for loop
This is a for loop
This is a for loop
For Each loop
public class JavaLoops { /** * JavaProgrammingForums.com */ public static void main(String[] args) { String[] myString = {"Java", "Programming", "Forums", ".com"}; // For each loop for(String s : myString){ System.out.print(s); } } } Example output:
JavaProgrammingForums.com
Do While loop
public class JavaLoops { /** * JavaProgrammingForums.com */ public static void main(String[] args) { // Do While loop int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 10); } } Example output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
While loop
public class JavaLoops { /** * JavaProgrammingForums.com */ public static void main(String[] args) { // While loop while(true){ System.out.println("I'm looping forever"); } } } Example output. Note that this loop will keep going forever.
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
I'm looping forever
....