Default Values and Initialization in Java

自作多情 提交于 2019-11-26 03:48:50

问题


Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.

public class Main {
    public static void main(String[] args) {
        int a;
        System.out.println(a);
    }
}

The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.

public class Main {
    static int a;
    public static void main(String[] args) {
        System.out.println(a);
    }
}

What could possibly go wrong with the first code? Does class instance variable behaves different from local variables?


回答1:


In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to default value .




回答2:


Read more carefully your reference:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

. . .

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.




回答3:


These are the main factors involved:

  1. member variable (default OK)
  2. static variable (default OK)
  3. final member variable (not initialized, must set on constructor)
  4. final static variable (not initialized, must set on a static block {})
  5. local variable (not initialized)

Note 1: you must initialize final member variables on EVERY implemented constructor!

Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is NOT valid:

private final int memberVar;

public Foo() {
    //invalid initialization of a final member
    init();
}

private void init() {
    memberVar = 10;
}

Note 3: arrays are Objects in Java, even if they store primitives.

Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.

I am attaching a code example, presenting the aforementioned cases:

public class Foo {
    //static and member variables are initialized to default values

    //primitives
    private int a; //default 0
    private static int b; //default 0

    //objects
    private Object c; //default NULL
    private static Object d; //default NULL

    //arrays (Note: they are objects too, even if they store primitives)
    private int[] e; //default NULL
    private static int[] f; //default NULL

    //what if declared as final?

    //primitives
    private final int g; //not initialized, MUST set in constructor
    private final static int h; //not initialized, MUST set in a static {}

    //objects
    private final Object i; //not initialized, MUST set in constructor
    private final static Object j; //not initialized, MUST set in a static {}

    //arrays
    private final int[] k; //not initialized, MUST set in constructor
    private final static int[] l; //not initialized, MUST set in a static {}

    //initialize final statics
    static {
        h = 5;
        j = new Object();
        l = new int[5]; //elements of l are initialized to 0
    }

    //initialize final member variables
    public Foo() {
        g = 10;
        i = new Object();
        k = new int[10]; //elements of k are initialized to 0
    }

    //A second example constructor
    //you have to initialize final member variables to every constructor!
    public Foo(boolean aBoolean) {
        g = 15;
        i = new Object();
        k = new int[15]; //elements of k are initialized to 0
    }

    public static void main(String[] args) {
        //local variables are not initialized
        int m; //not initialized
        Object n; //not initialized
        int[] o; //not initialized

        //we must initialize them before usage
        m = 20;
        n = new Object();
        o = new int[20]; //elements of o are initialized to 0
    }
}



回答4:


There are a few things to keep in mind while declaring primitive type values.

They are:

  1. Values declared inside a method will not be assigned a default value.
  2. Values declared as instanced variable or a static variable will have default values assigned which is 0.

So in your code:

public class Main {
    int instanceVariable;
    static int staticVariable;
    public static void main(String[] args) {
        Main mainInstance = new Main() 
        int localVariable;
        int localVariableTwo = 2;
        System.out.println(mainInstance.instanceVariable);
        System.out.println(staticVariable);
       // System.out.println(localVariable); //will throw compilation error
        System.out.println(localVariableTwo);

    }
}



回答5:


yes, instance variable will be initialized to default value, for local variable you need to initialize before use

public class Main {
      int instaceVariable; // Instance variable will be initalized to default value
    public static void main(String[] args) {
        int localVariable = 0; // Local Variable Need to initalize before use
    }
}



回答6:


Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.

There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.

If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.




回答7:


All member variable have to load into heap so they have to initialized with default values when an instance of class is created. In case of local variables, they don't get loaded into heap they are stored in stack until they are being used before java 7, so we need to explicitly initialize them.




回答8:


In java the default initialization is applicable for only instance variable of class member it isn't applicable for local variables.



来源:https://stackoverflow.com/questions/19131336/default-values-and-initialization-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!