Initialize a static final field in the constructor

Solution 1:

A constructor will be called each time an instance of the class is created. Thus, the above code means that the value of x will be re-initialized each time an instance is created. But because the variable is declared final (and static), you can only do this

class A {    
    private static final int x;

    static {
        x = 5;
    }
}

But, if you remove static, you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

OR this:

class A {    
    private final int x;

    {
        x = 5;
    }
}

Solution 2:

static final variables are initialized when the class is loaded. The constructor may be called much later, or not at all. Also, the constructor will be called multiple times (with each new object ), so the field could no longer be final.

If you need custom logic to initialize your static final field, put that in a static block

Solution 3:

Think about what happens the second time you instantiate an object. It tries to set it AGAIN, which is expressly prohibited by being a static final. It can only be set one time for the entire class, not instance.

You should set the value when you declare it

private static final x=5;

If you need additional logic, or more complex instantiation, this can be done in a static initializer block.

Solution 4:

static means that the variable is unique on the application. final means that it should be set only once.

If you set it in your constructor, you allow to set the variable more than once.

Hence you should intialize it directly or propose a static method to initialize it.

Solution 5:

Think about it. You could do this with your code:

A a = new A();
A b = new A(); // Wrong... x is already initialised

The correct ways to initialise x are:

public class A 
{    
    private static final int x = 5;
}

or

public class A 
{    
    private static final int x;

    static
    {
        x = 5;
    }
}