1

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?

Community
  • 1
  • 1
Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • How would you make an object as a compile time constant? Virtual machines, JITters etc will handle object creation in any way they want, so how would you make it so that everything works nicely? Still run constructors for them somehow? – Sami Kuhmonen Dec 23 '15 at 05:21
  • 1
    constructor can have custom code that can only execute at runtime – sidgate Dec 23 '15 at 05:22
  • Object creation itself is a *run-time* process. Strings (specifically String literals) are handled in a special way. They are generated when the class is getting loaded and added to the String constants pool. So, the value can be passed as part of the byte-code. – TheLostMind Dec 23 '15 at 05:25
  • @SamiKuhmonen: I got confused because if it was possible for Strings so why not for any other class? Stephen's answer below clarifies that its possible because Strings are handled in special way. – Sabir Khan Dec 23 '15 at 05:42

1 Answers1

2

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216