Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring arrays without using the 'new' keyword in Java

Is there any difference between the following two declarations?

int arr[] = new int [5]; 

and

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

Is arr1 declared on stack or on the heap?

like image 386
Muhammad Ali Qadri Avatar asked Aug 19 '16 06:08

Muhammad Ali Qadri


People also ask

Can we create array without new keyword in Java?

It is mere syntactic convenience to declare with the braces and no new . return {}; Objects (arrays are objects) are allocated on the heap.

Why new keyword is used in array in Java?

To create an array value in Java, you use the new keyword, just as you do to create an object. Here, type specifies the type of variables (int, boolean, char, float etc) being stored, size specifies the number of elements in the array, and arrayname is the variable name that is the reference to the array.

What are different ways to declare array in Java?

There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

Is new operator mandatory while initializing array in Java?

JAVA Programming Array can be initialized when they are declared. Array can be initialized using comma separated expressions surrounded by curly braces. It is necessary to use new operator to initialize an array.


1 Answers

There is the obvious difference that one has all zeros, and the other contains [1..5].

But that's the only difference. Both are 5-element int arrays, both are allocated in the same way. It is mere syntactic convenience to declare with the braces and no new.

Note that this form can only be used when the array is declared:

int[] blah = {} 

But not

int[] blah; blah = {}; 

or

return {}; 

Objects (arrays are objects) are allocated on the heap.

like image 115
Andy Turner Avatar answered Oct 02 '22 14:10

Andy Turner