Are default field values assigned by the compiler or the JVM?

前端 未结 2 1256
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 10:49

I have one question: in java we declare int,long,double etc.,(primitive data) or non primitive (object data), not initialized with default values, but at run time

2条回答
  •  隐瞒了意图╮
    2020-12-18 11:20

    The default values for fields are assigned by the JVM at runtime. From JLS 15.9.4 (emphasis mine):

    The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value.

    Of course, given that this behavior is standardized in the JLS, a compiler could conceivably take advantage of that to perform certain optimizations based on the assumption that uninitialized fields start with their default value.

    Fields are initialized to the equivalent of 0 in whatever type they are (null for reference types). This article gives a nice list:

    Data Type:              Default Value:
    boolean                 false 
    char                    \u0000 
    int,short,byte / long   0 / 0L 
    float / double          0.0f / 0.0d 
    any reference type      null
    

    Local variables are not given an initial value, and it is a compiler error to use them if they are not assigned a value through all possible code paths prior to use.

    Note that array elements are automatically initialized to default values as well when a new array is created (e.g. each element of new int[100] will be initialized to 0). This applies to both field and local array variables.

提交回复
热议问题