java: primitive arrays — are they initialized?

前端 未结 4 587
耶瑟儿~
耶瑟儿~ 2020-12-09 16:50

If I use a statement in my code like

int[] a = new int[42];

Will it initialize the array to anything in particular? (e.g. 0) I seem to reme

相关标签:
4条回答
  • 2020-12-09 17:18

    The array would be initialized with 42 0s

    For other data types it would be initialized with the default value ie.

    new boolean[42]; // would have 42 falses
    new double[42]; // would have 42 0.0 ( or 0.0D )
    new float[42]; // 42  0.0fs
    new long[42]; // 42  0Ls 
    

    And so on.

    For objects in general it would be null:

    String [] sa = new String[42]; // 42 nulls 
    
    Date [] da = new Date[42]; // 42 nulls
    
    0 讨论(0)
  • 2020-12-09 17:21

    At 15.10 Array Creation Expressions the JLS says

    [...] a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value

    and at 4.12.5 Initial Values of Variables it says:

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

    0 讨论(0)
  • 2020-12-09 17:22

    All elements in the array are initialized to zero. I haven't been able to find evidence of that in the Java documentation but I just ran this to confirm:

    int[] arrayTest = new int[10];
    System.out.println(arrayTest[5]) // prints zero
    
    0 讨论(0)
  • 2020-12-09 17:28

    When created, arrays are automatically initialized with the default value of their type - in your case that would be 0. The default is false for boolean and null for all reference types.

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