Declaring arrays without using the 'new' keyword in Java

前端 未结 5 2151
执念已碎
执念已碎 2020-12-14 17:15

Is there any difference between the following two declarations?

int arr[] = new int [5];

and

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


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 17:39

    I agree with the other answers, by far the most often you array will be allocated on the heap (no matter which of the two declarations you use). However, according to the top answer in Can Java allocate a list on stack?, “in special cases, the java virtual machine may perform escape analysis and decide to allocate objects … on a stack”. I believe that this is true. So the answer to your question is: It depends. Usually on the heap.

提交回复
热议问题