2.4 Initial Values for Variables

Default Values for Fields

Default values for fields of primitive data types and reference types are listed in Table 2.14. The value assigned depends on the type of the field.

Table 2.14. Default Values

Data Type

Default Value

boolean

false

char

'\u0000'

Integer (byte, short, int, long)

0L for long, 0 for others

Floating-point (float, double)

0.0F or 0.0D

Reference types

null

If no initialization is provided for a static variable either in the declaration or in a static initializer block (see Section 8.2, p. 336), it is initialized with the default value of its type when the class is loaded.

Similarly, if no initialization is provided for an instance variable either in the declaration or in an instance initializer block (see Section 8.2, p. 338), it is initialized with the default value of its type when the class is instantiated.

The fields of reference types are always initialized with the null reference value, if no initialization is provided.

Example 2.1 illustrates default initialization of fields. Note that static variables are initialized when the class is loaded the first time, and instance variables are initialized accordingly in every object created from the class Light.

Example 2.1 Default Values for Fields
public class Light {
    // Static variable
    static int counter;      // Default value 0 when class is loaded.

    // Instance variables
    int     noOfWatts = 100; // Explicitly set to 100.
    boolean indicator;       // Implicitly set to default value false.
    String  location;        // Implicitly set to default value null.

    public static void main(String[] args) {
        Light bulb = new Light();
        System.out.println("Static variable counter: "     + Light.counter);
        System.out.println("Instance variable noOfWatts: " + bulb.noOfWatts);
        System.out.println("Instance variable indicator: " + bulb.indicator);
        System.out.println("Instance variable location: "  + bulb.location);
        return;
    }
}

Output from the program:

Static variable counter: 0
Instance variable noOfWatts: 100
Instance variable indicator: false
Instance variable location: null

Initializing Local Variables of Primitive Data Types

Local variables are not initialized when they are created at method invocation, that is, when the execution of a method is started. They must be explicitly initialized before being used. The compiler will report attempts to use uninitialized local variables.

Example 2.2 Flagging Uninitialized Local Variables of Primitive Data Types
public class TooSmartClass {
    public static void main(String[] args) {
        int weight = 10, thePrice;                         // Local variables

        if (weight <  10) thePrice = 1000;
        if (weight >  50) thePrice = 5000;
        if (weight >= 10) thePrice = weight*10;            // Always executed.
        System.out.println("The price is: " + thePrice);   // (1)
    }
}

In Example 2.2, the compiler complains that the local variable thePrice used in the println statement at (1) may not be initialized. However, it can be seen that at runtime the local variable thePrice will get the value 100 in the last if-statement, before it is used in the println statement. The compiler does not perform a rigorous analysis of the program in this regard. It only compiles the body of a conditional statement if it can deduce the condition to be true. The program will compile correctly if the variable is initialized in the declaration, or if an unconditional assignment is made to the variable. Replacing the declaration of the local variables in Example 2.2 with the following declaration solves the problem:

int weight = 10, thePrice = 0;         // Both local variables initialized.

Initializing Local Reference Variables

Local reference variables are bound by the same initialization rules as local variables of primitive data types.

Example 2.3 Flagging Uninitialized Local Reference Variables
public class VerySmartClass {
    public static void main(String[] args) {
        String importantMessage;       // Local reference variable

        System.out.println("The message length is: " + importantMessage.length());
    }
}

In Example 2.3, the compiler complains that the local variable importantMessage used in the println statement may not be initialized. If the variable importantMessage is set to the value null, the program will compile. However, at runtime, a NullPointerException will be thrown since the variable importantMessage will not denote any object. The golden rule is to ensure that a reference variable, whether local or not, is assigned a reference to an object before it is used, that is, ensure that it does not have the value null. The program compiles and runs if we replace the declaration with the following declaration, which creates a string literal and assigns its reference to the local reference variable importantMessage:

String importantMessage = "Initialize before use!";

Arrays and their default values are discussed in Section 4.1 on page 101.