What is the difference between a null array and an empty array?

前端 未结 4 512
傲寒
傲寒 2020-12-29 23:39

If the individual elements of an int array are not initialized, what is stored in them by default? I apparently found that there is something like an empty array or a null a

相关标签:
4条回答
  • 2020-12-30 00:17

    An array has it's members initialized to their default values. For int the default is 0. For an Object it's null. A null array is a null Array Reference (since arrays are reference types in Java).

    JLS-4.12.5 Initial Values of Variables says in part

    For type int, the default value is zero, that is, 0.

    and

    For all reference types (§4.3), the default value is null.

    0 讨论(0)
  • 2020-12-30 00:18

    By default java initialized the array according to type declared. It is int then it is initialized to 0. If it is of type object like array of object then it is initialized to null.

    0 讨论(0)
  • 2020-12-30 00:24

    Technically speaking, there's no such thing as a null array; but since arrays are objects, array types are reference types (that is: array variables just hold references to arrays), and this means that an array variable can be null rather than actually pointing to an array:

    int[] notAnArray = null;
    

    An empty array is an array of length zero; it has no elements:

    int[] emptyArray = new int[0];
    

    (and can never have elements, because an array's length never changes after it's created).

    When you create a non-empty array without specifying values for its elements, they default to zero-like values — 0 for an integer array, null for an array of an object type, etc.; so, this:

    int[] arrayOfThreeZeroes = new int[3];
    

    is the same as this:

    int[] arrayOfThreeZeroes = { 0, 0, 0 };
    

    (though these values can be re-assigned afterward; the array's length cannot change, but its elements can change).

    0 讨论(0)
  • 2020-12-30 00:38

    If the individual elements of an int array are not initialized, what is stored in them by default?

    0

    empty array is array with 0 elements

    I haven't heard about null array but it is probably an array with non zero element reference which are null

    0 讨论(0)
提交回复
热议问题