Java - Loops

While writing a program, there may be a situation when you need to repeat a block of code again and again up to certain number of times or up to infinity. In such situation, you would need to write loop statements.

In Java, there are 3 types of loops available:

  1. for
  2. while
  3. do...while

Java - For Loop

For loop is useful when we know the starting value and ending value or the number of iterations. For loop is divided into 3 parts i.e. initialization, condition, and increment/decrement.

  • Initialization is the initial value from where the loop starts execution.
  • Condition will execute a loop until condition is false.
  • Increment/decrement will change the variable value for the next iteration.

Example 1: WAP to print counting 1 to 10 using For Loop.

public class ForLoop {
    public static void main(String[] args) {
        int i;
        //for(initialization; condition; increment/decrement)
        for(i=1;i<=10;i++)
            System.out.print("For loop " + i);
    }    
}
For Loop 1
For Loop 2
For Loop 3
For Loop 4
For Loop 5
For Loop 6
For Loop 7
For Loop 8
For Loop 9
For Loop 10

Java - While Loop

In While loop, initialization statement appears before the while loop begins, condition appears to test the loop, increment/decrement statement will appear inside the while loop to change the variable value for the next iteration. It is better if number of iteration is not known by the user.

Example 2: WAP to print counting 1 to 10 using While Loop.

public class WhileLoop {
    public static void main(String[] args) {
        int i=1; //initialization
        while(i<=10) //condition 
        {
            System.out.print("While Loop " + i);
            i++; //increment
        }
    }  
}
While Loop 1
While Loop 2
While Loop 3
While Loop 4
While Loop 5
While Loop 6
While Loop 7
While Loop 8
While Loop 9
While Loop 10

Java - Do While Loop

Do while loop is similar to while loop, only the different is that the condition appears in the end. So, the code is executed at least once, even if the condition is false.

Example 3: WAP to print counting 1 to 10 using Do While Loop.

public class WhileLoop {
    public static void main(String[] args) {
        int i=1; //initialization
        do
        {
            System.out.print("Do while loop "+i);
            i++; //increment
        }while(i<=10); //condition
}
Do while loop 1
Do while loop 2
Do while loop 3
Do while loop 4
Do while loop 5
Do while loop 6
Do while loop 7
Do while loop 8
Do while loop 9
Do while loop 10