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.
Special Cases
The following are some of the special scenarios that involve a looping statement.
Loops Examples
Now, we shall cover some examples to demonstrate the usage of loops in Java.
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
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
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.