I am wondering why sometimes I see code with static variable? When is it better to use static variable instead of "normal" variable? If its value do not change from an istance to another, is it not better to use final variable?
-
Thats quite opinion based and broad don´t you think? – Alexander Heim Sep 14 '17 at 07:51
-
When you have some values that you need on a Class level. example if you have some static methods then you values need to be static too. – Anders Sørensen Sep 14 '17 at 07:52
4 Answers
The point in using static variables is not the same as final ones.
Final-declared variables (static or not) cannot be modified. They are often used as "reference values" or constants.
Static-variables (and methods) are therefore needed as "shared content". For instance, say each person in the office likes to drink coffee. Are we better of with everyone bringing his own coffee machine ? Or are we better sharing one such machine for the entire office ?
Obviously you want to chose the shared option. In a programming idiom, this would translate to having a static
variable in the Office
class representing the unique CoffeeMachine
.
Off-topic but surely you wouldn't want to make this coffee machine final
. What if someone breaks it ? You would need to replace it, and thus change the variable.

- 1,019
- 6
- 18
static means, that the variable is in all instances of this Object the same.
The Main example is a Object-Counter.
class foo{
private static int count = 0;
public foo()
{
count ++;
}
public static getCountOfObj()
{
return count;
}
}
So you can edit it on all foo-Objects.

- 95
- 10
static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..
Variables declared static are commonly shared across all instances of a class.

- 153
- 6
I assume you mean static fields.
static
fields are associated with the class, whereas instance fields are associated to an object (aka class instance).
If a field is marked as final
(works for both instance and static fields), then it cannot be reassigned.
So each has its own different role to play.

- 2,567
- 3
- 22
- 38