Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between final variables vs static final variables

Tags:

java

I was just studying about final data members and i thought what would be the difference final variables vs static final variables ??


I understand that a field that is both static and final has only one piece of storage, and final variable will have storages associated with every instance.

But even if i declare a variable only final, then it remains the same for all the objects as i need to initialize them in the program itself and not at the run time.


So, basically there is no difference between the two except for the memory related issue ??

like image 387
Chitransh Saurabh Avatar asked Jun 01 '12 04:06

Chitransh Saurabh


3 Answers

But even if i declare a variable only final, then it remains the same for all the objects as i need to initialize them in the program itself and not at the run time.

No, non-static final members can be initialized in the constructor. They cannot be re-assigned after that.

like image 151
Hari Menon Avatar answered Nov 18 '22 21:11

Hari Menon


The final means you can assign only one time the value to the variable. The final can be use in many scopes and is very useful, in a object property you must (and forced) to set the value on the declaration, or in the constructor or in the initialization block of the object.

And the static is to set the scope of the variable, that means in a class property that value is storage inside the class, and can be access even without an object, when you use static final or final static you must (and forced) to set the value on the declaration or inside a static initialization code of the class.

Example:

public class NewClass {

    static final int sc = 123; //I recommend to use this declaration style.
    final static int scc;
    final int o = 123;
    final int oo;
    final int ooo;

    static {
        scc = 123;
    }

    {
        oo = 123;
    }

    public NewClass() {
        ooo = 123;
    }

    void method(final int p) {
//        p=123; //Error, the value is only assigned at the call of the method.

        final int m = 123;
        final int mm;
        mm = 123;
//        mm = 456; //Error, you can set the value only once.
        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(m + p); //You still can reach the variables.
            }
        }).start();
    }
}
like image 22
Daniel De León Avatar answered Nov 18 '22 19:11

Daniel De León


final variables : A variable declared final will be a constant, its value can not be changed, and can be initialized in the constructor.

static final variable : This must be initialized, either during the declaration or in the static initializer block.

like image 2
Kumar Vivek Mitra Avatar answered Nov 18 '22 19:11

Kumar Vivek Mitra