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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With