Given the following simple code in Java.
final class Demo
{
public static final long serialVersionUID=1L;
static
{
System.out.println("Static constructor invoked.");
}
}
public final class Main
{
public static void main(String... args)
{
System.out.println(Demo.serialVersionUID);
}
}
In this simplest of Java code, the static
constructor is expected to be invoked, when the class Demo
is initialized through the main()
method through Demo.serialVersionUID
but it does not.
If this program were run without modifications, the output would only be 1
(the message - Static constructor invoked. as specified in the static
block would not be displayed).
If we want the message to be printed as specified in the static
initializer then, we need to modify the declaration statement in the Demo
class,
public static final long serialVersionUID=1L;
to either,
public static long serialVersionUID=1L;
removing the final
modifier or,
public static final Long serialVersionUID=1L;
changing the primitive type long
to its corresponding wrapper type Long
.
So, why does it behave this way? Why does it not display the message in the static
constructor without the specified changes to the program?