Will a static final variable of a primitive or String type, that is assigned a value at definition be considered as a REAL compile-time constant by the Java Compiler?
Will such a variable gain the performance bonus a compile-constant has in other languages, say C++?
Are enums of primitive or String values get treated like constants by the compiler?
From what I understand, it is always good to substitute variables with constants when it doesn’t effect workings of the script and so I wonder at the empty meaning for the const keyword in java.
Thanks in advance.
Yes, they’re compile-time constants. For example, the code
will be compiled to bytecode which doesn’t even contain the code inside the
if. It will be removed by the compiler.And you have to recompile all the classes referencing the constant if you decide to change its value.
Note however that it’s only the reference that can’t be modified. The content of the object (if it’s mutable), can be changed. For example, the content of the array or StringBuilder in the following code may be modified:
Your question about enums doesn’t make sense. There is no enum of primitive or STring. Each enum defines its own class.