Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Final Variable in Java [duplicate]

Tags:

java

static

final

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

like image 985
darksky Avatar asked Sep 27 '11 02:09

darksky


People also ask

Can we have static final variable in Java?

The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.

Is a static variable common to all instances of the class?

static variable are class variables and its not specific to any instance. Simply we can say its common for all the instance of the class.

How do I set a static final variable in Java?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Can static final variables be changed?

A static variable is common for all instances of the class. A final variable can not change after it has been set the first time. So a static final variable in Java is common for all instances of the class, and it can not be changed after it has been set the first time.


2 Answers

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

like image 129
Oh Chin Boon Avatar answered Oct 07 '22 19:10

Oh Chin Boon


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

like image 40
Lavanya Mohan Avatar answered Oct 07 '22 18:10

Lavanya Mohan