The do-while construct is a loop structure which repeatedly executes one or some statements until a condition becomes false. In other words, it repeats the statements while the condition is still true.

 

1. Syntax of do...while construct in Java:

The first form (there is only while keyword):

while (condition is true) {
    // statements
}

 

The second form (there are both do and while keywords):

do {
    // statements
} while (condition is true); 

 

2. Some Rules about do...while construct in Java:

    • The while construct starts executing the statements in its body only if the condition is true. The statements may not be executed (if condition is false from start).
    • The do-while construct always execute the statements in its body at least one time, even if the condition is false from start.
    • If there is only one statement in the body, the curly braces can be removed.

 

3. Java do..while Examples

The following code uses a while loop prints out 10 numbers from 1 to 10:

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

The following do-while loop reads input from command line until an empty string is entered:

String input = null;
do {
    System.out.print("Enter input: ");
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    input = reader.readLine();
    System.out.println("Your input: " + input);
} while (!input.equals(""));

 

Related Tutorials:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment