Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed some text, updated references to Java 7

...

In general, you should declare each variable on its own line with an explanatory comment regarding its role. Although it is not required for conformance with this guideline, this practice is also recommended in the Code Conventions for the Java Programming Language, Section 6.1, "Number Per Line" [Conventions 2009].

When more than one variable is declared in a single declaration, ensure that both the type and the initial value of each variable are self-evident.

This guideline applies to

Noncompliant Code Example (Initialization)

...

Declaration of multiple variables per line can reduce code readability and lead to programmer confusion.

When more than one variable is declared in a single declaration, ensure that both the type and the initial value of each variable are self-evident.

Declarations of loop indices should be included within a for statement (although this, technically, violates Note that the declaration of a loop counter in a for statement is in violation of this guideline because the declaration is not on its own line with an explanatory comment about the variable's role. However, declaration of loop indices in for statements is not only a common idiom but also provides the benefit of restricting the scope of the loop index to the for loop itself. This is a specific reason to relax this guideline.Declarations of loop indices should be included within a for statement):

Code Block
bgColor#ccccff
public class Example {
  void function() {
    int mx = 100; // some max value

    for (int i = 0; i < mx; ++i ) {
      /* ... */
    }

  }
}

...