In Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private
and final
, the difference is the static
attribute.
What's better? And why?
In Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private
and final
, the difference is the static
attribute.
What's better? And why?
Static variable belongs to the class (which means all the objects share that variable). Non static variable belongs to each objects.
As you can see above example, for "final int" we can assign our variable for each instance (object) of the class, however for "static final int", we should assign a variable in the class (static variable belongs to the class).
If you use static the value of the variable will be the same throughout all of your instances, if changed in one instance the others will change too.
Here is my two cents:
Example:
The key is that variables and functions can return different values.Therefore final variables can be assigned with different values.
Since a variable in a class is declared as final AND initialised in the same command, there is absolutely no reason to not declare it as static, since it will have the same value no matter the instance. So, all instances can share the same memory address for a value, thus saving processing time by eliminating the need to create a new variable for each instance and saving memory by sharing 1 common address.
private static final will be considered as constant and the constant can be accessed within this class only. Since, the keyword static included, the value will be constant for all the objects of the class.
private final variable value will be like constant per object.
You can refer the java.lang.String or look for the example below.
//Output:
Furthermore to Jon's answer if you use static final it will behave as a kind-of "definition". Once you compile the class which uses it, it will be in the compiled .class file burnt. Check my thread about it here.
For your main goal: If you don't use the NUMBER differently in the different instances of the class i would advise to use final and static. (You just have to keep in mind to not to copy compiled class files without considering possible troubles like the one my case study describes. Most of the cases this does not occur, don't worry :) )
To show you how to use different values in instances check this code: