Home  >  Article  >  Java  >  Bodiless loops in Java

Bodiless loops in Java

WBOY
WBOYOriginal
2024-07-19 04:26:50584browse

Laços sem corpo em Java

Concept

  • In Java, a loop may not have an associated body, as a null statement is syntactically valid.

Utility

  • Bodyless loops can be used for operations that are completely handled in the loop expression.

-Example of a loop without a body

  • The example below adds the numbers 1 to 5 using a for loop without a body:
class Empty3 {
    public static void main(String args[]) {
        int i;
        int sum = 0;
        // soma os números até 5
        for (i = 1; i <= 5; sum += i++);
        System.out.println("Sum is " + sum);
    }
}

The program output is: Sum is 15

Loop analysis

The sum is performed completely within the for loop expression.
The iteration expression sum += i++ does the addition and increment of i:
sum += i++;

Breaking down the expression

  • This expression can be understood as two parts:
  • sum = sum + i; - Add i to sum. i++; - Increments i.

Importance

  • Instructions of this type are common in professional Java programs.
  • Understanding and breaking down these expressions makes understanding the code easier.

The above is the detailed content of Bodiless loops 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