do keyword in Java

The ” do ” keyword specifies a loop whose condition is checked at the end of each iteration.

Syntax is as below

1
2
3
4
5
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:

1
2
3
while (boolean_condition {
        // statements
}
while (boolean_condition {
        // statements
}


2. There are both do and while keywords:

1
2
3
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:

1
2
3
4
5
6
7
8
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":

1
2
3
4
5
6
7
8
9
10
11
12
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.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on