do keyword in Java
The ” do
” keyword specifies a loop whose condition is checked at the end of each iteration.
Syntax is as below
- do
- {
- <statements>
- }
- while (boolean_condition);
do { <statements> } while (boolean_condition);
The do-while is a loop structure which repeatedly executes the statements until a condition becomes false.
In other words, it repeats the statements as long as the condition is true.
There are two forms:
1. There is only while keyword:
- while (boolean_condition {
- // statements
- }
while (boolean_condition { // statements }
2. There are both do and while keywords:
- do {
- // statements
- } while (boolean_condition);
do { // statements } while (boolean_condition);
Rules :
The while statement executes the statements only if the condition is true.
The statements will not be executed if condition is false at the start.
The do-while statement always execute the statements in its body at least one time, even if the condition is false at the start.
Examples
The following code uses a while loop prints out 100 numbers from 1 to 100:
- int i = 1;
- while (i <= 100) {
- System.out.println(i);
- i++;
- }
int i = 1; while (i <= 100) { System.out.println(i); i++; }
The following do-while loop reads input from command line until user enters the string "done":
- String userInnput = null;
- do {
- System.out.print("Enter input string: ");
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
- userInnput = reader.readLine();
- System.out.println("Your input string: " + userInnput);
- } while (!userInnput.equals("done"));
String userInnput = null; do { System.out.print("Enter input string: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); userInnput = reader.readLine(); System.out.println("Your input string: " + userInnput); } while (!userInnput.equals("done"));
In this case, first time, statements will be executed without any condition check and subsequent execution will check the condition and executes only if condition returns true.