5

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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.