What are class variables, instance variables and local variables in Java?


A variable provides us with named storage that our programs can manipulate. Java provides three types of variables.

  • Class variablesClass variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

  • Instance variablesInstance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.

  • Local variables − Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.

Example

Live Demo

public class VariableExample{
   int myVariable;
   static int data = 30;
   
   public static void main(String args[]){
      int a = 100;
      VariableExample obj = new VariableExample();
      
      System.out.println("Value of instance variable myVariable: "+obj.myVariable);
      System.out.println("Value of static variable data: "+VariableExample.data);
      System.out.println("Value of local variable a: "+a);
   }
}

Output

Value of instance variable myVariable: 0
Value of static variable data: 30
Value of local variable a: 100

Ali
Ali

Updated on: 13-Sep-2023

29K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements