Search code examples
javavariablesstaticconstantsfinal

can the final keyword alone be used to define a constant in java


The java documentation mentioned that

The static modifier, in combination with the final modifier, is also used to define constants.

I was just wondering, can the final keyword alone be used to define a constant in java. I know that variable declared with final keyword and without static keyword can't be changed, but does it count as a constant?


Solution

  • You need the static keyword to eliminate the context of the Class instance. Take a look at the following code:

    public class Main {
    
    public static final String CONST;
    
    static {
        if((System.currentTimeMillis() % 2) == 0) {
            CONST = "FOO";
        }
        else {
            CONST = "BAR";
        }
    }
    
    public final String CONST2;
    
    public Main(){
        if((System.currentTimeMillis() % 2) == 0) {
            CONST2 = "FOO";
        }
        else {
            CONST2 = "BAR";
        }   
    }
    

    }

    While creating multiple instances of Main will result in different values for CONST2, CONST will be initialized when the class is loaded and so stays the same over several instances of Main.

    The more interesting is that you may even have a static final variable with different values in case that multiple ClassLoaders are involved.

    So, a constant in Java is a final static variable that is initialized with a constant value.