What is a Variable? In simple words, a variable can be defined as the container which holds the value. Also, a Variable is assigned with a data type. A variable determines the size and range of values, that can be stored within the memory.

There are three types of Variables we use in Java

1. Local Variable:

Local variables declared inside the body of the method. we use these variables only within that method. Example:

public class Test {

   public void localvar() {

      int num = 0;

      num = num + 7;

      System.out.println(“Final num is : ” + num);



   public static void main(String args[]) {

      Test test = new Test();



Output: Final num is 7
If You want to learn step by step tutorial, watch the video:

2. Instance Variable:

A variable declared inside the class but outside the body of the method, is called instance variable. Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed.

class Marks

//These variables are instance variables.

//These variables are in a class and are not inside any function

          int engMarks;

          int mathsMarks;

          int phyMarks;


class InstanceVar


          public static void main(String args[])


                   Marks obj = new Marks();

                    obj.engMarks = 50;

                    obj.mathsMarks = 80;

                    obj.phyMarks = 90;

                    System.out.println(“Marks for object:”);





Output: Marks for object: 50,80,90

3. Static Variable/Class Variable:

Static variables are also called class variables and this is much similar to the instance variables. it is declared with the static keyword in a class, but outside a method, constructor or a block.

class Emp {
// static variable salary

          public static double salary;

          public static String name = “Mohan”;


public class EmpDemo


       public static void main(String args[]) {

//accessing static variable without object

       Emp.salary = 10000;

       System.out.println(Emp.name + “‘s average salary:” + Emp.salary);



Output: Mohan’s average salary : 10000

Connect with us: