In this tutorial you will learn about the Java Loops and its application with practical example.
Java Loops
The loop statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. Java loops statements are very useful to iterate over a collection/list of items or to perform a task multiple times. In Java, we have the following loop statements available-
Java for Loop
The for loop is used when we want to execute a block of code known times. In Java, the basic for loop is similar to what it is in C and C++. The for loop takes a variable as an iterator and assign it with an initial value, and iterates through the loop body as long as the test condition is true.
Syntax :-
1 2 3 |
for(Initialization; Condition; incr/decr){ // loop body } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { System.out.println("W3Adda - Java for loop"); for(int ctr=1;ctr<=5;ctr++){ System.out.println(ctr); } } } |
Output:-
Java While Loop
The while loop will execute a block of statement as long as a test expression is true.
Syntax:-
1 2 3 4 |
while(condition) { // loop body } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static void main(String[] args) { int ctr =1; int maxCtr =5; System.out.println("W3Adda - Java while loop"); while(ctr<=maxCtr){ System.out.println(ctr); ctr = ctr+1; } } } |
Output:-
Java do…while Loop
The do…while statement executes loop statements and then test the condition for next iteration and executes next only if condition is true.
Syntax:-
1 2 3 |
do{ // loop body } while(condition); |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class Main { public static void main(String[] args) { int ctr =1; int maxCtr =5; System.out.println("W3Adda - Java do while loop"); do{ System.out.println("Hello World! Value Is : "+ctr); ctr = ctr+1; }while(ctr<=maxCtr); } } |
When we run the above java program, we see the following output –
Output:-