Static Variable vs Instance Variable
Let us understand the differences between static and instance variable.
Java language uses variables in different scopes: static scope, local scope, block scope. Java has different ways of storing data either as primitive data types or as Objects. Class specifies type of a object. Static variable is defined generically for the entire class and not for a specific object. Hence Static variables belong to a class and hence has the same value for all objects of the class. Instance (object) variables belong to a specific object.
Static variable | Instance variable |
---|---|
A static variable is a property of a class. | An instance variable is a property of an instance. |
A static variable is created only once when the classloader loads the class. | An instance variable is created everytime an instance is created. |
A static variable is used when you want to store a value that represents all the instances like count, sum, average etc. | An instance variable is used to store a value that represents property of single instance. |
Declaring an static variable
static int countOfOrders;
Declaring an instance variable
String OrderId;
Let us consider the following example:
public class Order{ //static variable static int countOfOrders; //instance variable String orderId;
public static void main(String args[]){ Order orderInst = new Order(); //Assigning to static variable Order.countOfOrders = 10; //Assigning to instance variable orderInst.orderId="Ord1_11Nov2017_3578923"; String name="Jan";//simple local variable. it is not instance and not static. } }
Assigning to static variable
Order.countOfOrders = 10;
orderInst.countOfOrders= 11;
Both the above assignments work. However, Using the class name is the preferred approach.
Assigning to instance variable
orderInst.orderId="Ord1_11Nov2017_3578923";