Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java arrays initializing after declare

Tags:

java

arrays

I saw someone initialize and array like this in java

int[] s;

s = new int[]{ and put the list here..}

versus

int[] s = { the list here} 

Are these both acceptable way of doing it?

like image 930
rubixibuc Avatar asked Oct 04 '11 06:10

rubixibuc


People also ask

Does Java automatically initialize arrays?

In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0 .

Does Java automatically initialize arrays to zero?

Yes, for primitive types(except boolean and char) it will be default to ZERO.

How are arrays initialized in Java?

If you want to initialize an array, try using Array Initializer: int[] data = {10,20,30,40,50,60,71,80,90,91}; // or int[] data; data = new int[] {10,20,30,40,50,60,71,80,90,91}; Notice the difference between the two declarations. When assigning a new array to a declared variable, new must be used.


1 Answers

Yes, both are equally valid ways of creating a java integer array. The second version is just a shortcut syntax of the first version.

More on that here : http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

like image 90
Narendra Yadala Avatar answered Sep 19 '22 00:09

Narendra Yadala