Empty arrays automatically initialize contents?

后端 未结 5 1702
滥情空心
滥情空心 2021-01-16 13:35

How come

int alone;
System.out.println(alone);

Gives errors but

 int[] arr = new int[1];
 System.out.println(arr[0]);


        
相关标签:
5条回答
  • 2021-01-16 13:53

    It depends on where it was declared (inside a class vice inside a function). If it is a class member variable it will be initialized to its default. 0 for numeric types(0.0 for float types / double), null for Strings, false for boolean,and null for Objects. If it is declared inside of a function it would remain uninitialized in the case of int alone. In terms of an array it will always initialize the values contained within it.

    0 讨论(0)
  • 2021-01-16 13:57

    There are two separate by similar issues involved here. First note that all variable types have a default value, which differs depending on the type. There are at least two times where these defaults are used: 1) declaring a member variable and 2) initializing an array with the new operator.

    Notice that if you simply declare a local array variable without initializing it with new, then you get the same error as when you declare a simple int variable. This is because all local variables must be initialized. They do not get an automatic default value.

    On the other hand, member variables do get a default value. Similarly, when you create an array object by using the new operator, the elements of the array are initialized to the appropriate default value.

    0 讨论(0)
  • 2021-01-16 14:03

    From the language standard

    Otherwise, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

    And the default values are:

    • For type byte, the default value is zero, that is, the value of (byte)0.

    • For type short, the default value is zero, that is, the value of (short)0.

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

    • For type long, the default value is zero, that is, 0L.

    • For type float, the default value is positive zero, that is, 0.0f.

    • For type double, the default value is positive zero, that is, 0.0d.

    • For type char, the default value is the null character, that is, '\u0000'.

    • For type boolean, the default value is false.

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

    0 讨论(0)
  • 2021-01-16 14:04

    Yes, for primitive type number arrays, it initializes with 0, for boolean[], it initializes with false, for char[], it initializes with NULL(ASCII value 0) and for objects [] including String[] its initializes with null.

    0 讨论(0)
  • Yes, for primitive types(except boolean and char) it will be default to ZERO. If object type it will be default to null.

    This java tutorial may help you.

    NOTE: as woot4Moo answered, this is for only instance variables. If local variable, then it won't be default to any.

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