Kars Kars - 1 month ago 4x
Java Question

Understanding static variable initialization in Java

public class InstanceBuilder {

private static final InstanceBuilder INSTANCE = new InstanceBuilder();

private static String name = null;

private InstanceBuilder() {
System.out.println("Setting cons()");
name = "Testing";

public static String getName() {
return name;

public class Driver {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("value is " + InstanceBuilder.getName());



Setting cons()
value is null

Why does it print value as null even though I have set the static variable in constructor and it is called as expected. If I try to print in constructor, it is printing "Testing", but if i call from public static method, it is null. I know if I change it to INSTANCE.name, it works.
But I want to understand why it is not working if I directly access static variable since same copy should be shared.
What I am missing here?


Because the value of name is getting modified after the constructor invocation as per the declaration order.

Lets see what is happening:

1) When you call InstanceBuilder.getName(), InstanceBuilder class is getting loaded. As part of that process INSTANCE and name instance variables are getting initialized.

2) While initializing INSTANCE,

private static final InstanceBuilder INSTANCE = new InstanceBuilder();

constructor of InstanceBuilder class is getting invoked and Setting cons() statement is getting printed and name variable is initialized with Testing.

3) Next name is again getting re-initialized with null due to the statement

private static String name = null;

so when the method call returns to Driver class, value of name is null and null is getting printed. So even though name is declared as static, static has no role in that context.


Check the below link on the order of which class members should be declared