Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array initialization guarantees

Does Java guarantee array initialization?

Let's say I use the code char[] uuid = new char[36];, would each element be guaranteed to be initialized to 0?

like image 579
jldupont Avatar asked Jul 01 '12 00:07

jldupont


People also ask

What happens when you initialize an array in Java?

Array Initialization in Java This allocates the memory for an array of size 10 . This size is immutable. Java populates our array with default values depending on the element type - 0 for integers, false for booleans, null for objects, etc. Let's see more of how we can instantiate an array with values we want.

Does Java automatically initialize arrays to zero?

if the elements in the array are integers (int), each element in the array will be automatically initialized to 0. if the elements in the array are Strings, each element will be initialized to the null character (null). if the elements in the array are boolean, each element will be initialized to false.

What does initializing an array do?

Initializing an arrayIn order to store values in the array, we must initialize it first, the syntax of which is as follows: datatype [ ] arrayName = new datatype [size]; There are a few different ways to initialize an array. Look at the following examples to get a better idea about array initialization.

Do arrays initialize to null in Java?

Array elements are initialized to 0 if they are a numeric type ( int or double ), false if they are of type boolean , or null if they are an object type like String .


2 Answers

Yes. JLS §10.3 ensures that all elements of an array are set to their initial values, which by JLS §4.12.5 is guaranteed to be 0, false, or null.

like image 166
Jeffrey Avatar answered Nov 09 '22 22:11

Jeffrey


Yes, it does guarantee initialization. JLS section 10.3

like image 2
Jochen Avatar answered Nov 09 '22 21:11

Jochen