+ 1

why?

To make a variable constant why do we declare final static?? why not only final?

11th Apr 2017, 6:02 AM
Somnath Ghosh
Somnath Ghosh - avatar
4 ответов
+ 7
static members are shared using heap memory. means many instances of a class share the same memory address. so it doesn't need separate memory allocation for each objects rather all objects of same class share a single variable. so static takes less memory, efficient, and faster processing. since constants are to be same for all class so it is also declared as static
11th Apr 2017, 6:07 AM
Sandeep Chatterjee
+ 3
the reason why is answered,but you don't have to use static final at all to declare constants,use enums they are better ,efficient and most importantly error free. Eg: let say you have a constant like public static final int x=0; public static final int y=1; and a method that takes these constants public void methodX(int a){ } here the user is able to pass another argument outside you constants which is not wanted HERE IS THE SOLUTION enum const{ X,Y; } public void methodX(const a){ } here the user is not able to pass another argument than your enum constants.
11th Apr 2017, 8:29 AM
Haileyesus Shitalem
Haileyesus Shitalem - avatar
0
so we add static also because it takes less memory and efficient ?? Using only final, we also can make a variable constant ? and in heap memory, i think..we store object only...can we store static variable also?? Or class store all static members ?
11th Apr 2017, 6:44 AM
Somnath Ghosh
Somnath Ghosh - avatar
0
you have to differentiate here. constants which universally apply (like pi, e or gravitation of earth) should be final static. these constants apply for all implementations and all instances. hence they don't NEED to be stored on the stack where the object is stored but rather on the head, where the class information is stored. that's the meaning of static in this context. however if you need a "constant" which is dependent on the instance you need to make it final without static. this is a write-once variable.
11th Apr 2017, 7:40 AM
Petja Boigk
Petja Boigk - avatar