Sabir Khan
Sabir Khan

Reputation: 10142

Why compile time constants limited to only primitives and Strings?

This is just out of curiosity and I guess I know the answer too but just wish to validate and know other viewpoints.

Compile time constants and variables tells that compile time constants are limited to only primitive types and Strings. Why so even if I declare a reference of some type A as final ( final A aObj = new A(); )? Is it because classes are not loaded yet or something else? There are so many other immutable classes in JDK , Complete List of immutable JDK classes? , why those not included?

Upvotes: 1

Views: 934

Answers (1)

Stephen C
Stephen C

Reputation: 719336

Because the construction of an object (mutable or immutable) can have side-effects that have to occur at runtime. String is exceptional, in that the Java language assumes that this can never happen. It is also exceptional in that it is one of the few classes that the Java language specification depends on; i.e. in the handling of literals, and the semantics of certain kinds of switch statement (Java 6 and later).

The latter is particularly relevant to the "compile time constant", since the switch arm expressions are required to be compile time constant expressions.

A couple of other factors:

  • handling of compile-time constants is more complexity for both the compiler and the runtime JVM

  • compile-time constants can have unexpected behavior when code is compiled incrementally, so limiting the cases where that behavior occurs is beneficial (for programmers),

  • there is probably not much practical benefit in making more types eligible to be compile-time constants.

Upvotes: 2

Related Questions