Loops in Java

Looping

In Programming, looping is used to repeat the block of the code. E.g., if you want to print your name 100 times, you can use a loop. It will save your time and reduce duplicate code.

Types Of Loop

  • For Loop
  • While Loop
  • Do While Loop

For Loop

This is the most common type of loop. You can use for loop to run a block of code multiple times according to condition.

Syntax

for(initialization; condition; increment/decrement){
 statements;
}
  • Initialization is executed (one time) before the execution of the code block.
  • Condition defines the condition for executing the code block.
  • Increment/decrement is executed (every time) after the code block has been executed.
Example to print 1 to 10 using for loop.

public class Main {
    public static void main(String[] args) {
    for(int i=1; i<=10; i++){
    System.out.println(i);
    }
      
    }
}
Show Output
Example to print your name ten times.
public class Main {
    public static void main(String[] args) {
        for(int i=1; i<=10; i++){
    System.out.println("John Doe");
    }
    }
}
Show Output
Example to print 10 to 1 using for loop.
public class Main {
    public static void main(String[] args) {
        for(int i=10; i>=1; i--){
    System.out.println(i);
    }
    }
}
Show Output

While Loop

While loop is used to run a block of code while a certain condition is true. You must write conditions first before statements.

Syntax

while(condition){
     statements;
}
Example to print 1 to 10 using while loop
public class Main {
    public static void main(String[] args) {
        int i =1;
        while(i<=10){
        System.out.println(i);
        i++;
        }
        }
    }
Show Output
Example to print 10 to 1 using while loop
public class Main {
    public static void main(String[] args) {
        int i =1;
        while(i<=10){
        System.out.println(i);
        i++;
        }
    }
}
Show Output

Do While Loop

Do while loop is used to run a block of code multiple times. In do-while loop, you execute statements first and check conditions last.

Info

Note: If the condition is false do-while loop executes statements at least one time.

Syntax

do{
   statements;
}while(condition);
Example to print 1 to 10 using do-while loop
public class Main {
    public static void main(String[] args) {
         int i =1;
         do{
            System.out.println(i);
            i++;
         }while(i<=10);
    }
}
Show Output
Example to print 10 to 1 using do while loop
public class Main {
    public static void main(String[] args) {
         int i =10;
         do{
             System.out.println(i);
             i--;
        }while(i>=1);
    }
}
Show Output