In this Java tutorial, you will learn about looping statements in Java programming, and how these looping statements are used to automate a task to run for a specific number of times, or execute a specific block of code for each item in a collection.

Java Loops

Java Looping statements are used to repeat a set of actions in a loop based on a condition.

There are many loop statements in Java. The following tutorials cover these looping statements in detail.

Loop Control Statements

Java also provides some statements to control a loop. The following tutorials cover these loop control statements.

ADVERTISEMENT

Special Cases

The following are some of the special scenarios that involve a looping statement.

Examples

Now, we shall cover some examples to demonstrate the usage of loops in Java.

1. While Loop

In the following program, we will use while loop to print “hello world” to console output in a loop.

Example.java

public class Example {

	public static void main(String[] args) {
		int i = 0;
		while(i < 3){
			System.out.println("hello world");
			i++;
		}
	}
}

Output

hello world
hello world
hello world

2. Do-while Loop

In the following program, we write a do-while loop statement to print “hello world” to console three times.

Example.java

public class Example {
	public static void main(String[] args) {
		int i = 0;
		do{
			System.out.println("hello world");
			i++;
		} while(i < 3);
	}
}

Output

hello world
hello world
hello world

3. For Loop

In the following program, we will use for loop and print a string three times to console output.

Example.java

public class Example {
	public static void main(String[] args) {
		for(int i = 0; i < 3; i++){
			System.out.println("hello world");
		}
	}
}

Output

hello world
hello world
hello world

Conclusion

In this Java Tutorial, we have learnt different looping statements available in Java, some special statements that control loops, and example use cases that use loops.