Java中的默认值和初始化

时间:2022-10-05 17:01:51

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.

线System.out.println(一个);将是指向变量a的错误,表示变量a可能没有初始化,而在给定的引用中,integer将具有0作为默认值。但是,下面的代码将实际打印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?

第一个代码有什么可能出错?类实例变量是否与局部变量不同?

8 个解决方案

#1


51  

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

在第一个代码示例中,a是一个主要的方法局部变量。方法使用局部变量之前需要初始化它们。

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

在第二个代码示例中,a是类成员变量,因此它将被初始化为默认值。

#2


52  

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.

在声明字段时,并不总是需要分配值。声明但未初始化的字段将被编译器设置为合理的默认值。一般来说,这个默认值是0或null,这取决于数据类型。然而,依赖这些默认值通常被认为是糟糕的编程风格。

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


14  

These are the main factors involved:

这些是所涉及的主要因素:

  1. member variable (default OK)
  2. 成员变量(默认好)
  3. static variable (default OK)
  4. 静态变量(默认好)
  5. final member variable (not initialized, must set on constructor)
  6. 最终成员变量(未初始化,必须在构造函数上设置)
  7. final static variable (not initialized, must set on a static block {})
  8. 最终静态变量(未初始化,必须在静态块{}上设置)
  9. local variable (not initialized)
  10. 局部变量(而不是初始化)

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

注意1:必须在每个实现的构造函数上初始化最终成员变量!

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:

注意2:您必须在构造函数本身的块中初始化最终的成员变量,而不是调用初始化它们的另一种方法。例如,这是无效的:

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.

注意3:数组是Java中的对象,即使它们存储基元。

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

注意4:初始化数组时,它的所有项都被设置为默认值,独立于成员或本地数组。

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


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. 方法中声明的值不会被赋值为默认值。
  3. Values declared as instanced variable or a static variable will have default values assigned which is 0.
  4. 被声明为instanced变量或静态变量的值将具有赋值为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


2  

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


1  

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.

当您在类级别声明一个变量时,有一个很大的区别(作为一个成员ie)。作为字段)和方法级别。

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


0  

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.

所有成员变量都必须加载到堆中,以便在创建类的实例时使用默认值初始化。在本地变量的情况下,它们不会被加载到堆中,直到它们在java 7之前被使用,所以我们需要显式地初始化它们。

#8


0  

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

在java中,默认初始化只适用于类成员的实例变量,不适用于本地变量。

#1


51  

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

在第一个代码示例中,a是一个主要的方法局部变量。方法使用局部变量之前需要初始化它们。

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

在第二个代码示例中,a是类成员变量,因此它将被初始化为默认值。

#2


52  

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.

在声明字段时,并不总是需要分配值。声明但未初始化的字段将被编译器设置为合理的默认值。一般来说,这个默认值是0或null,这取决于数据类型。然而,依赖这些默认值通常被认为是糟糕的编程风格。

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


14  

These are the main factors involved:

这些是所涉及的主要因素:

  1. member variable (default OK)
  2. 成员变量(默认好)
  3. static variable (default OK)
  4. 静态变量(默认好)
  5. final member variable (not initialized, must set on constructor)
  6. 最终成员变量(未初始化,必须在构造函数上设置)
  7. final static variable (not initialized, must set on a static block {})
  8. 最终静态变量(未初始化,必须在静态块{}上设置)
  9. local variable (not initialized)
  10. 局部变量(而不是初始化)

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

注意1:必须在每个实现的构造函数上初始化最终成员变量!

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:

注意2:您必须在构造函数本身的块中初始化最终的成员变量,而不是调用初始化它们的另一种方法。例如,这是无效的:

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.

注意3:数组是Java中的对象,即使它们存储基元。

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

注意4:初始化数组时,它的所有项都被设置为默认值,独立于成员或本地数组。

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


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. 方法中声明的值不会被赋值为默认值。
  3. Values declared as instanced variable or a static variable will have default values assigned which is 0.
  4. 被声明为instanced变量或静态变量的值将具有赋值为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


2  

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


1  

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.

当您在类级别声明一个变量时,有一个很大的区别(作为一个成员ie)。作为字段)和方法级别。

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


0  

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.

所有成员变量都必须加载到堆中,以便在创建类的实例时使用默认值初始化。在本地变量的情况下,它们不会被加载到堆中,直到它们在java 7之前被使用,所以我们需要显式地初始化它们。

#8


0  

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

在java中,默认初始化只适用于类成员的实例变量,不适用于本地变量。