next up previous
Next: Compound statements Up: Simple statements Previous: Assignment and expression statements

Local variable declarations

Generally local variable declarations should be on separate lines; however, an exception is allowable for temporary variables that do not require initializers. For example,
int i, j = 4, k; // WRONG
int i, k;        // acceptable
int j = 4;

Use lazy-declaration of variables. Declare variables closest to their first point of use. For better readability and efficiency, you don’t have to declare all the local variables right at the beginning of a block ({}).

    int i = 0;
    for (i = 0; i < 100; i++) {
        boolean check = false;
    }
should be
    for (int i = 0; i < 100; i++) {
        boolean check = false;
    }

Whenever possible, do not separate the variable declaration and variable initialization. This is not possible for try/catch blocks.

        // WRONG
        Set set;
        set = new HashSet(); 

        // RIGHT
        Set set = new HashSet();



Dennis Seah Mon Jul 17 11:43:42 2006