Initializing Local Variables of Primitive Data Types – Declarations

Initializing Local Variables of Primitive Data Types

Local variables are variables that are declared in methods, constructors, and blocks. They are not initialized implicitly when they are allocated memory at method invocation—that is, when the execution of a method begins. The same applies to local variables in constructors and blocks. Local variables must be explicitly initialized before being used. The compiler will report an error only if an attempt is made to use an uninitialized local variable.

Example 3.2 Flagging Uninitialized Local Variables of Primitive Data Types

Click here to view code image

public class TooSmartClass {
  public static void main(String[] args) {
    double weight = 10.0, thePrice;                    // (1) Local variables

    if (weight <  10.0) thePrice = 20.50;
    if (weight >  50.0) thePrice = 399.00;
    if (weight >= 10.0) thePrice = weight * 10.0;      // (2) Always executed
    System.out.println(“The price is: ” + thePrice);   // (3) Compile-time error!
  }
}

In Example 3.2, the compiler complains that the local variable thePrice used in the print statement at (3) may not have been initialized. If allowed to compile and execute, the local variable thePrice will get the value 100.0 in the last if statement at (2), before it is used in the print statement. However, in Example 3.2, the compiler cannot guarantee that code in the body of any of the if statements will be executed and thereby the local variable thePrice is initialized, as it cannot determine whether the condition in any of the if statements is true at compile time.

We will not go into the details of definite assignment analysis that the compiler performs to guarantee that a local variable is initialized before it is used. In essence, the compiler determines whether a variable is initialized on a path of control flow from where it is declared to where it is used. This analysis can at times be conservative, as in Example 3.2.

The program will compile correctly if the local variable thePrice is initialized in the declaration, or if an unconditional assignment is made to it. Replacing the declaration of the local variables at (1) in Example 3.2 with the following declaration solves the problem:

Click here to view code image

double weight = 10.0, thePrice = 0.0; //    (1′) Both local variables initialized

Replacing the condition in any of the if statements with a constant expression that evaluates to true will also allow the compiler to ensure that the local variable thePrice is initialized before use in the print statement.