Java do-while construct examples
- Details
- Written by Nam Ha Minh
- Last Updated on 16 August 2019   |   Print Email
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:
- Java for loop construct
- All keywords in Java
- Summary of primitive data types in Java
- Summary of operators in Java with examples
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- Java Access Modifiers Examples: public, protected, private and default
- 10 Java Core Best Practices Every Java Programmer Should Know
- Java Variables Passing Examples - Pass-by-value or Pass-by-reference?
Comments