I have read that final variables in Java should be instantiated to compile time constant expression. I couldn't understand what is compile time constant expression.
class A {
int i;
int j = i * 5;
}
Is `i * 5 a compile time constant expression?
A "compile time constant expression" is a value that can be calculated during compilation. For example, int MINUTES_IN_DAY = 24 * 60;
As for your reading that final variables should always be instantiated in that form: that's an incorrect generalisation. There are many instances where you need a final
to be evaluable at runtime, such as when setting up Runnable
s.
Note that static final variables do not need to be compile-time constants either: you can initialise them using static initialisers .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.