When I print the constant
in main
, the static
block does not execute, but when I print stat
, it does execute. Is there any importance to static final
in Java?
package com.test.doubt;
class Doubt {
public static final int constant = 123;
public static int stat = 123;
static {
System.out.println("Static Block");
}
}
public class MyProgram {
public static void main(String[] args) {
System.out.println(Doubt.constant);
}
}
Your code isn't initializing the Doubt
class, precisely because Doubt.constant
is a constant. Its value is baked into MyProgram
at compile-time - you could even delete Doubt.class
after compilation and your program would still run.
Run
javap -c com.test.doubt.MyProgram
to have a look at exactly what your code looks like after compilation.
See section 15.28 of the JLS for what constitutes a constant expression. For example, this would still be a constant:
public static final String FOO = "Foo";
and so would all of these:
public static final String FOO = "Foo";
public static final String BAR = "Bar";
public static final String FOOBAR = FOO + BAR;
... but this wouldn't be
public static final String NOT_A_CONSTANT = "Foo".substring(0, 1);
The static final int
will get compiled directly into your code as its value. That is to say, the JVM sees and is executing:
System.out.println(123);
and you're not touching your aptly-named Doubt
class at all (this is an argument for not specifying constants in this fashion, btw. If you change that value you have to recompile every referencing class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With