Search code examples
javaandroidstaticfinal

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.


Solution

  • static -  Only use when a variable which is used globally 
    final -  Only use when you need to declare a value as constant 
    
    static final - Only use when a value is globally used and it is a constant.
    
    : - Here global means across all the instances of a java class