Variable Types in java

Variable is nothing but a name or keyword which occupies space in the memory. Variables are classified in 3 types.

  • Local Variable
  • Instance (or non-static) variable
  • Static or Class variables
  • Parameters or arguments

Local Variables: 

  1. Local variables can be declared in the method,Constructor or block.
  2. It has scope till the end of execution of method,Constructor or block i.e. it will be destroyed once exit the method,Constructor or block.
  3. It is mandatory to initialize them, otherwise it throws error at compile time.
  4. Access modifier can not be used with them.
public class Demo1 {	
	public static void main(String[] args) {
		int age = 0;	// Initializing local variable age	
		age = age +2;			
	}
}

Instance/Non-static Variables:

  1. These variables are declared inside the class, but outside the method,Constructor or block.
  2. These are available to all method,Constructor or block.
  3. Access modifier can be used with them.
  4. If not initialized, then default values will be assigned to them like false for boolean, 0 for integer,null for object reference. Execute the below program for understanding.
public class Demo1 {	
	String name;  //instance variables
	boolean val;  //instance variables
	int age;      //instance variables
	
	public static void main(String[] args) {
		Demo1 d = new Demo1();
		d.checkVariables();
	}
	
	public void checkVariables(){
		System.out.println(name +"--"+ val +"--"+ age);
	}
	
}

Static Variables: 

  1. Static  keyword is used to define the static variables.
  2. These are declared at the class level.
  3. It can not be declared as local i.e. not inside a method, constructor or a block.
  4. It can be accessed with the class name i.e. classname.staticvariable.
public class Demo1 {	
	static String name; //	static variable
	public static void main(String[] args) {
	Demo1.name = "Shekhar";
	}	
}

Parameters or arguments: These are the variables which are passed as arguments in method. These variables can be used anywhere in the method and access memory during execution of methods. As you can see in above program , main method used args which is a parameter or argument.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’. Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...