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:
package com.javahonk; public class InstanceClassSample { String name = "Java HOnk"; public void testName(){ //instanceClassSample and instanceClassSample2 will have it own copy of name InstanceClassSample instanceClassSample = new InstanceClassSample(); InstanceClassSample instanceClassSample2 = new InstanceClassSample(); System.out.println(instanceClassSample.name); System.out.println(instanceClassSample2.name); } }
- Static variable sample class:
package com.javahonk; public class StaticSampleClass { static String name = "Java HOnk"; public void testName(){ //instanceClassSample and instanceClassSample2 will have only one copy of name shared between them StaticSampleClass instanceClassSample = new StaticSampleClass(); StaticSampleClass instanceClassSample2 = new StaticSampleClass(); } }
Reference: