Java: Why can't return array using {..} without new operator?

前端 未结 5 684
忘掉有多难
忘掉有多难 2021-01-04 05:58

I have searched a lot on the website, but didn\'t find any related question. So I believe it is not a duplicate.

I know we can initialize an array with 3 ways:

5条回答
  •  梦毁少年i
    2021-01-04 07:02

    char[ ] charAr=new char[10];
    

    Is a proper array declaration. You could assign charAr to another char array.

    char[ ] charAr=new char[]{'a','b','c'};
    

    Syntax where you do both declaration and initialization in one line. You can reassign this to a new char array.

    char[ ] charAr={'a', 'b', 'c'};
    

    Is a array literal. You can assign literal value only where you define the array. You cannot reassign this to a new char array.

    You cannot return array literals because during compile time, the compiler does not know the type of elements you are returning.

提交回复
热议问题