I'm indebted to this answer for the idea.
The following code compiles, but certainly shouldn't. It uses the value of x
before it's been initialised. If you remove the StaticAssign.
qualifier then it no longer compiles.
public class StaticAssign {
public static final int x;
static {
System.out.println(StaticAssign.x);
x = 5;
}
public static void main(String[] args) {}
}
On my machine, this consistently prints 0
. If I change the type of x
to String
, it consistently prints null
.
The question is: will it definitely print 0
or null
, or might it access uninitialised memory and print out something else?
And even if this code gets through the compiler, why isn't it picked up by the JVM?
Is there a way to do nasty things based on this?