Search code examples
javastaticfinal

Static Final Variable in Java


Possible Duplicate:
private final static attribute vs private final attribute

What's the difference between declaring a variable as

static final int x = 5;

or

final int x = 5;

If I only want to the variable to be local, and constant (cannot be changed later)?

Thanks


Solution

  • Just having final will have the intended effect.

    final int x = 5;
    
    ...
    x = 10; // this will cause a compilation error because x is final
    

    Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x