Variable types in java

There are 3 types of variable in java:

  • Local variables : any variables which are defined in side methods, constructor or block (scoop).  the variables will declare and initialized when method invoked and destroyed when method has completed. these variable can access only in side it own method.
  • Class variables (static variable): any variables which are declared in side class but out side method, with static keyword . It can be accessed by class name with variable name (cannot access from instance object).
  • Instance variables: any variables which are defined in side class but out side any method (not local variables) and not static variable. these variables are initialize when the class instantiated. they can be accessed from in side method, constructor, or blocks of that particular class.
public class VariableTypes {
//	 instance variable
	int instancVariable;
//	static variable
	static int staticVar;
	public VariableTypes() {
//		access instance variable
		instancVariable = 2;
		
	}
	public void display() {
//		local variable 
		int x =50;
		System.out.println("Welcome to www.learning2night.com");
		System.out.println("Testing Variables Type :");
		System.out.println("Instance variable :"+instancVariable);
		System.out.println("Local variable "+x);

	}
	
	public static void main(String[] args) {
//		access static variable
		VariableTypes.staticVar = 100;
		VariableTypes vt = new VariableTypes();
		vt.display();
		System.out.println("Static Variavle : "+VariableTypes.staticVar);
	}
}

Output:

Welcome to www.learning2night.com
Testing Variables Type :
Instance variable :2
Local variable 50
Static Variavle : 100

 

 

Add a Comment

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