23. What is the difference between an instance variable and a static variable? Give an example where you might use a static variable


Static Variable

Instance Variable

Class variables are called static variables. There is only one occurrence of a class variable per JVM per class loader.

When a class is loaded the class variables (aka static variables) are initialized.


Instance variables are non-static and there is one occurrence of an instance variable in each class instance (i.e. each object).



A static variable is used in the singleton pattern. (Refer Q45 in Java section). A static variable is used with a final modifier to define constants.


No comments:

Post a Comment