do...while Loop

suggest change

The do...while loop differs from other loops in that it is guaranteed to execute at least once. It is also called the “post-test loop” structure because the conditional statement is performed after the main loop body.

int i = 0;
do {
    i++;
    System.out.println(i);
} while (i < 100); // Condition gets checked AFTER the content of the loop executes.

In this example, the loop will run until the number 100 is printed (even though the condition is i < 100 and not i <= 100), because the loop condition is evaluated after the loop executes.

With the guarantee of at least one execution, it is possible to declare variables outside of the loop and initialize them inside.

String theWord;
Scanner scan = new Scanner(System.in);
do {
    theWord = scan.nextLine();
} while (!theWord.equals("Bird"));

System.out.println(theWord);

In this context, theWord is defined outside of the loop, but since it’s guaranteed to have a value based on its natural flow, theWord will be initialized.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Basic Control structures:
* do...while Loop
* Break

Table Of Contents
8 Arrays
10 Maps
11 Strings
15 Basic Control structures
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap