Home  >  Article  >  Java  >  What is the meaning and usage of do in java

What is the meaning and usage of do in java

下次还敢
下次还敢Original
2024-05-01 17:27:53339browse

do is the keyword to create a do-while loop in Java. Its characteristics are: the loop condition is checked after the loop body is executed; no matter whether the condition is true or not, the loop body will be executed at least once; different from the while loop , the execution order is to execute the loop body first and then check the conditions.

What is the meaning and usage of do in java

What is do in Java?

do is a keyword in Java that is used to create do-while loops. A do-while loop is similar to a while loop, but its loop condition is checked after the loop body is executed.

Usage

<code class="java">do {
    // 循环体
} while (循环条件);</code>
  • Loop body: Contains statements to be executed repeatedly.
  • Loop condition: Boolean condition checked after the loop body is executed. If the condition is true, the loop continues; if it is false, the loop terminates.

Difference from while loop

The main difference between do-while loop and while loop is:

  • Execution Sequence: In a do-while loop, the loop body is always executed once first, and then the loop condition is checked; in a while loop, the loop condition is checked first, and then the loop body is executed.
  • Execute at least once: The do-while loop executes the loop body at least once, even if the loop condition is false when executed for the first time; while the while loop may not execute the loop body if the loop The condition is initially false.

Example

<code class="java">int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 5);</code>

In this example, the loop body is executed once (output i is 0), and then the loop condition is checked (i < 5) . The loop condition is true, so the loop continues executing with outputs i being 1, 2, 3, and 4. When i equals 5, the loop condition becomes false and the loop terminates.

The above is the detailed content of What is the meaning and usage of do in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn