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

前端 未结 5 698
忘掉有多难
忘掉有多难 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:50

    1st question is:what is the name of {'a','b','c'} kind of stuff? Is it called array literals?

    No Array literals in Java, they are filling array with elements, i.e initialization.

    2nd question is: what is the difference between new char[]{'a','b','c'} with {'a','b','c'}?

    That first one called as * inline array declaration*.

    With second you can assign it to a array which already with a defined type.

    Example by me here :https://stackoverflow.com/a/19658726/1927832

    3rd question is: why I can't return a newly created array with {'a','b','c'}? I have to return new char[]{'a','b','c'}.

    Because in the first case the type is missing, and compiler doesn't know which type of elements they are.

    4th question: both new char[10] and new char[]{'a','b','c'} are constructors of array, right?

    That is creating an array of chars with specified length.

提交回复
热议问题