4

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?

Tiny
  • 27,221
  • 105
  • 339
  • 599
  • I mainly wanted to know the reason why `long` (primitive) needs to be modified to `Long` (wrapper) to display that message. – Tiny Apr 21 '14 at 15:38
  • One of the requirements for a field to be a compiletime constant is that it must be either a primitive or a string. – Bhesh Gurung Apr 21 '14 at 15:41
  • Marko Topolnik provided an excellent answer to exactly that question on the question I linked. It boils down to `static final` primitives or `String`s being compile-time constants, so their values get hardcoded into where they're referenced, rather than actually being referenced - which avoids the need to actually load the class. – JonK Apr 21 '14 at 15:42

0 Answers0