What is difference between these two array declarations?

前端 未结 5 1970
自闭症患者
自闭症患者 2021-01-11 21:05

It seems these two declarations are the same:

int[] array1 = {11, 22, 33};

and

int[] array2 = new int[] {11, 22, 33};
         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 21:31

    Since you are providing the initializer in the same line in which you are declaring, you cam omit the new operator.

    // This is OK

    int[] i32Array = { 1,2,3,4,5 };

    // This is NOT

    int[] i32Array; i32Array = { 1,2,3,4,5 };

    If your definition and initiation happens in different line you will have to do this

    i32Array = new int[] { 1,2,3,4,5 };

    So, technically speaking, it is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable

提交回复
热议问题