Java Reference
In-Depth Information
In general, you should declare each variable on its own line with an explanatory com-
ment regarding its role. While not required forconformance with this guideline, this prac-
tice is also recommended in the Code Conventions for the Java Programming Language,
§6.1, “Number Per Line” [Conventions 2009].
This guideline applies to
Local variable declaration statements [JLS 2013, §14.4]
Field declarations [JLS 2013, §8.3]
Field (constant) declarations [JLS 2013, §9.3]
Noncompliant Code Example (Initialization)
This noncompliant code example might lead a programmer or reviewer to mistakenly be-
lieve that both i and j are initialized to 1. In fact, only j is initialized, while i remains
uninitialized:
int i, j = 1;
Compliant Solution (Initialization)
In this compliant solution, it is readily apparent that both i and j are initialized to 1:
Click here to view code image
int i = 1; // Purpose of i...
int j = 1; // Purpose of j...
Compliant Solution (Initialization)
In this compliant solution, it is readily apparent that both i and j are initialized to 1:
int i = 1, j = 1;
Declaring each variable on a separate line is the preferred method. However, multiple
variables on one line are acceptable when they are trivial temporary variables such as ar-
ray indices.
Noncompliant Code Example (Different Types)
Inthisnoncompliantcodeexample,theprogrammerdeclaresmultiplevariables,including
an array, on the same line. All instances of the type T have access to methods of the Ob-
ject class. However, it is easy to forget that arrays require special treatment when some
of these methods are overridden.
Search WWH ::




Custom Search