![]() |
VOOZH | about |
In Java, when a variable is declared with the static keyword. Then, a single variable is created and shared among all the objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. These are the main scenarios when we use the static variable most of the time:
Important points:
from m1 Inside static block Value of a : 20 from main
Explanation:
Aspect | Static Variable | Instance Variable |
|---|---|---|
Definition | The static variable is is belong to the class and It shared the same instance in all the reference where it is used. | The instance variable is belong to the instance of a class (object). |
Memory | The static variable is allocated on the time of class loading in the memory only once. | The instance variable is created when we create an object of a class. |
Modification | If we update the value of the static variable it will reflect to all the instances where it is In use. | The instance variable has the separate copies in each of it's instances. |
Access | We can directly access it without creating an object of a class. | The instance variable is only access via object of the class. |
Scope | The scope of the static variable is in the entire class. We can access through all the instances of the class. | It's scopeis limited to the specific instance of the defined class. |
Related articles:Are Static Local Variables Allowed in Java?