Sahil Mahajan Mj Sahil Mahajan Mj - 1 month ago 6
Java Question

When to choose variables to declare as final static

I have used final and static variables as well. what i found about these variables is,

final variable




  • A final variable can only be initialized once, either via an initializer or an assignment statement.

  • Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.



what variables should i declare as final-

Most often i use those variables whose value is constant universally and can never changed, such as the value of PI.

public static final double PI = 3.141592653589793;


static variables




  • These are those variables which belongs to the class and not to object(instance).

  • Static variables are initialized only once , at the start of the execution .

  • A single copy to be shared by all instances of the class

  • A static variable can be accessed directly by the class name and doesn’t need any object.



what variables should i declare as final-

Most of the time, i use those variables which i want to initialize only once and use them in the enitre class.

When to use final static variable



Now, i came across a term
final static
in one of my database project. I found that some of the database objects or even database version were declared as statci final.

static final String DATA_BASE = "BackUpDatabase.db";
static final int DATA_BASE_VERSION = 1;


Now, my question is what variables should we declare as
final
or
static
or
final static
, as using either of them could have solved the issue, then wyh to use both together.

Answer

Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared.

Declaring them as static final will help you to create a CONSTANT as @Vulcan told. Only one copy exists which can be accessed anywhere.