Static Instance Variable Difference Example

Static Instance Variable Difference Example

Static Variable Instance Variable
Static variable is one per class Instance variable one per object
Every object of that class will share same static variable Every object of that class will have its own copy of instance variable
Static variable is initialized when JVM loads the class Instance variable initialize when object get created
Static method cannot access non static method or variable because it doesn’t have any state Instance variable can access static variable or method (But because static is class level and it does not have state so access should be done through class)
Static variable can survive longer (Garbage collection) Instance variable life is lesser in for garbage collection
Static is one per class so memory consumption is less Instance variable is one per object so it’s takes for every object
Static variable only one memory location is allocated irrespective to no object created Instance variable each object one memory location is allocated
  • Instance variable sample class:

  • Static variable sample class:

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *