Java Do While Loop

    This loop will work when the number of iterations is not known and the code has to run at least once. This loop will execute the program a number of times until the condition is false. The do-while loop will get executed at least once because the condition is checked after the first iteration at the end of the program block. Syntax

    do{  
    //code to be executed  
    }
    while(condition);

    Example

    public class DoWhileExample {  
    public static void main(String[] args) {  
        int i=1;  
        do{  
            System.out.println(i);  
        i++;  
        }while(i<=3);  
    }  
    }

    Output

    1
    2
    3

    Infinitive do-while loop This loop will execute infinite time if we pass the true condition. You can exit the infinite loop by pressing ctrl+c. Syntax

    do{  
    //code to be executed  
    }
    while(true);

    Example

    public class DoWhileExample2 {  
    public static void main(String[] args) {  
        do{  
            System.out.println("infinitive do while loop");  
        }while(true);  
    }  
    }

    Output

    infinitive do while loop 
    infinitive do while loop 
    infinitive do while loop 
    ctrl+c

    Conclusion

    To sum it up, the do-while loop in Java is an Exit Control loop. It iterates the part of a program repeatedly until the specified condition holds True. It is ideal to use the do-while loop when the number of iterations is not specified and you have to execute the loop at least once. We hope this article helped you develop a good understanding of the do-while loop in Java. Also, we have discussed do-while and infinitive do-while loops with appropriate examples. People are also reading: