Java

What Is Do Keyword In Java

A do-while loop is created by combining the do and while keywords.

do{
   //body of do-while
}while(condition);

Example of do keyword

public class JavaExample {
  public static void main(String[] args) {
    int i = 0;
    do {
      System.out.println(i);
      i++;
    }while (i < 6);
  }
}

Output:

do keyword in java example output

Why we need do while when we have while loop?

The following are the key distinctions between do-while and a while loop:

  • The statements inside a while loop are executed when the condition has been verified.
  • The do-while loop initially performs the statements before checking the condition.

Do-while loops are said to run at least once for each condition.

public class JavaExample {
  public static void main(String[] args) {
    //do while
    int i = 0;
    do {
      System.out.println("do-while");
      i++;
    }while (i > 1000);

    //while
    int j = 0;
    while (j > 1000){
      System.out.println("while");
      j++;
    }
  }
}

Output: Since you can see, the while loop did not run for the exact same loop condition and situation, but the do-while loop did run once as it tested the condition after the initial execution.

do-while

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button