Static Final Variable in Java

133,904

Solution 1

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

Solution 2

Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword.

Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name.

As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final').

Similar question is private final static attribute vs private final attribute

Hope it helps

Solution 3

In first statement you define variable, which common for all of the objects (class static field).

In the second statement you define variable, which belongs to each created object (a lot of copies).

In your case you should use the first one.

Solution 4

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

Share:
133,904
darksky
Author by

darksky

C, C++, Linux, x86, Python Low latency systems Also: iOS (Objective-C, Cocoa Touch), Ruby, Ruby on Rails, Django, Flask, JavaScript, Java, Bash.

Updated on June 12, 2020

Comments

  • darksky
    darksky almost 4 years

    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