Cithel Cithel - 6 months ago 18
Java Question

Is a new String() of a constant byte array evaluated at compile time?

I have a constant byte array, for instance

static final byte[] myArray = "something".getBytes();


used to write somewhere (XML, JMS...), and I want to use the value "something" as a String without declaring a new constant (I know I should).

I was wondering, if I write

anObject.setMessage(new String(myArray));


is the expression
new String(myArray)
evaluated at compile time ?

The java language specification states that only String literals are evaluated at compile time, this is not a String literal but I don't see why it wouldn't be evaluated at compile time.

Answer

is the expression new String(myArray) evaluated at compile time ?

No. It's evaluated at runtime.

You can have it evaluated at compile time if you use:

static final String myString = "something";

and

anObject.setMessage(myString);

I don't see why it wouldn't be evaluated at compile time.

This is described in JLS Sec 15.9.4:

Every time the [class instance creation] expression is evaluated, a fresh object is created.

But aside from that, it's not a constant expression if you use a byte[] as a parameter: even though you can't assign a new value to the static final array reference, you can still change the array elements. This should be of concern particularly as the myArray field is (or at least appears) non-private.

Because String is immutable, a static final String is a constant. However, this doesn't mean that it could be evaluated at compile time if you use a string, because of the JLS quote above.