MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java do-while loop


Do-while loop:


Do- while loop is similar to a while loop except for the fact that it is guaranteed to execute at least once.
Use a do-while loop when the exact number of iterations is unknown, but you need to execute a code block at least once.
After executing a part of a program for once, the rest of the code gets executed on the basis of a given boolean condition.
Syntax :
/* do {

            //code

} while (condition);            //Note this semicolon */

Example :


int i=1;  
do{  
System.out.println(i);  
i++;  
}while(i<=10); 

Difference Between while loop and do-while loop :


  • while – checks the condition & executes the code.

  • do-while – executes the code at least once and then checks the condition. Because of this reason, the code in the do-while loop executes at least once, even if the condition fails.

  • Flow control of do-while loop :



    Example


    package com.company;
    
    public class cwh_22_ch4_do_while {
        public static void main(String[] args) {
            int b = 10;
            do {
                System.out.println(b);
                b++;
            }while(b<5);
    
            int c = 1;
            do{
                System.out.println(c);
                c++;
            }while(c<=45);
    
        }
    }
    

    Output

    10
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45


    Conclusion

    In this page (written and validated by ) you learned about Java do-while loop . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java for Loop.



    Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


    Share On:


    Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.