CONTENTS | PREV | NEXT | Java Code Conventions |
Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.
void MyMethod() {
int int1; // beginning of method block
if (condition) {
int int2; // beginning of "if" block
...
}
}
The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:
for (int i = 0; i < maxLoops; i++) { ...
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:
int count;
...
func() {
if (condition) {
int count; // AVOID!
...
}
...
}