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. do
  2.  {
  3.         <statements>
  4.  }
  5. while (boolean_condition);
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. while (boolean_condition {
  2.         // statements
  3. }
while (boolean_condition {
        // statements

2. There are both do and while keywords:

  1. do {
  2.           // statements
  3. } 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.


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

  1. int i = 1;
  3. while (i <= 100) {
  5.     System.out.println(i);
  7.     i++;
  8. }
int i = 1;

while (i <= 100) {



The following do-while loop reads input from command line until user enters the string "done":

  1. String userInnput = null;
  3. do {
  4.     System.out.print("Enter input string: ");
  6.     BufferedReader reader = new BufferedReader(new InputStreamReader(;
  8.     userInnput = reader.readLine();
  10.     System.out.println("Your input string: " + userInnput);
  12. } while (!userInnput.equals("done"));
String userInnput = null;

do {
    System.out.print("Enter input string: ");

    BufferedReader reader = new BufferedReader(new InputStreamReader(;

    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
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

Connect with me on Facebook for more updates

Share this article on