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

前端 未结 5 657
忘掉有多难
忘掉有多难 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条回答
  •  悲哀的现实
    2021-01-04 06:47

    In the declaration:

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

    the array {'a', 'b', 'c'} is called an array initializer. It is described in Section 10.6 of the Java Language Specification. It can only be written like that (without the new char[] in front of it) as part of a variable declaration.

    In any other place (including a return statement), you need to use an array creation expression. These are described in Section 15.10 of the JLS. You can use either an array initializer or an array creation expression to initialize a variable when it is declared. That's why the new char[] appears to be optional when you declare the variable.

    Regarding your 4th question: they technically are not "constructors" (which has a specific meaning in Java terminology) but yes, they both construct arrays (or, perhaps more accurately, they both create arrays).

提交回复
热议问题