Static Instance Variable Difference Example

Static Instance Variable Difference Example

Static VariableInstance Variable
Static variable is one per classInstance variable one per object
Every object of that class will share same static variableEvery object of that class will have its own copy of instance variable
Static variable is initialized when JVM loads the classInstance variable initialize when object get created
Static method cannot access non static method or variable because it doesn’t have any stateInstance 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 lessInstance variable is one per object so it’s takes for every object
Static variable only one memory location is allocated irrespective to no object createdInstance 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:

Leave a Reply

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