Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are array initialized in Java?

When I write this

 String[] fruits = {"Apple", "Pear"};

I would expect that at compile time the array and the strings are created, like it would happen for similar code in C. Is it correct? Are array and their content generally created at compile time or at run-time?

like image 706
Paolo Avatar asked Nov 09 '12 15:11

Paolo


2 Answers

Arrays, which are objects in Java, are created. This can only occur at runtime.

Note that many objects are created in a Java program, and your object creations occurs only after the VM itself is initialized. One static array initialization isn't going to put a noticeable burden on your performances.

If you don't change the array and you have many instances, be sure to declare it as static :

static String[] fruits = {"Apple", "Pear"};

Note also an important difference with what could be a statically compiled array : the java array is mutable. You can't change its length but you can change its elements (or nullify them). A java array, even final static, isn't really constant.

like image 142
Denys Séguret Avatar answered Nov 09 '22 01:11

Denys Séguret


Arrays are special objects in java. So, they will be created at runtime.

As per Java Language Specification

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2)

JLS 15.10 provides more information on array creation expressions.

like image 40
kosa Avatar answered Nov 09 '22 01:11

kosa