Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: primitive arrays -- are they initialized?

Tags:

java

arrays

If I use a statement in my code like

int[] a = new int[42];

Will it initialize the array to anything in particular? (e.g. 0) I seem to remember this is documented somewhere but I am not sure what to search for.

like image 724
Jason S Avatar asked May 31 '10 15:05

Jason S


People also ask

How do you initialize a primitive array in Java?

To provide initial object references or primitive values other than the default, you have to address each element in the array. In the following code, we declare and create an array of Rectangle objects, and then create the Rectangle objects for each element: 1. Rectangle hotSpots[] = new Rectangle[10]; 2.

Are arrays in Java automatically initialized?

In Java, all array elements are automatically initialized to the default value.

Are arrays automatically initialized?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero. If an array is to be completely initialized, the dimension of the array is not required.

Can primitive types be instantiated?

Can array of primitive data type be instantiated? Yes.


3 Answers

At 15.10 Array Creation Expressions the JLS says

[...] a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value

and at 4.12.5 Initial Values of Variables it says:

For type int, the default value is zero, that is, 0.

like image 144
p00ya Avatar answered Sep 28 '22 16:09

p00ya


When created, arrays are automatically initialized with the default value of their type - in your case that would be 0. The default is false for boolean and null for all reference types.

like image 28
Bozhidar Batsov Avatar answered Sep 28 '22 17:09

Bozhidar Batsov


The array would be initialized with 42 0s

For other data types it would be initialized with the default value ie.

new boolean[42]; // would have 42 falses
new double[42]; // would have 42 0.0 ( or 0.0D )
new float[42]; // 42  0.0fs
new long[42]; // 42  0Ls 

And so on.

For objects in general it would be null:

String [] sa = new String[42]; // 42 nulls 

Date [] da = new Date[42]; // 42 nulls
like image 35
OscarRyz Avatar answered Sep 28 '22 17:09

OscarRyz