What Is An Instance In Java?

In Java, when we are working on a project or we are writing some code we use classes and methods in order to perform different actions and solve different problems with the help of Java. Now every program written in Java needs variables to store the values and allocate the memory, so Java has three types of variables: local, static, and instance.

Now In this write-up, we are going to see:

  • What is the difference between instance, local and static variables?
  • What is an instance variable in Java?

What is the difference between instance, static, and local variables?

A local variable is the one that is declared inside the functions, constructors, or blocks and can only be used inside the function, constructor, or a block in which it is created. A static variable is the one that needs a static keyword for declaration inside a class but outside a block, method, or a constructor. These variables are allocated in static memory.

What is an instance variable in Java?

In Java, the variable is said to be an instance variable if its declaration is done inside a class but outside a block, a method, or a constructor. Instance variables can be used by every method, constructor, or block inside a class. When the object for the class is created, JVM allocates a memory to the instance variables. These variables are always allocated in heap memory. These variables also contain default values like 0, false and null. We can also use access specifiers with instance variables.


public class arry {
    int k = 30;
    public static void main(String[] args) {
        arry getval = new arry();
        System.out.println("This value of an instance variable is " + getval.k);

In this code, we have declared an instance variable inside the arry class but outside the main method. Then we create the object of arry class getval and try to access the value of the instance variable with the help of the class object.


The output shows that the instance variable is created outside the main method but inside a class and accessed with the help of the object which is created for the arry class.


In Java, the instance variable is the one that is declared inside a class and outside a method. This type of variable is allocated in heap memory and accessed through the object of a class. In this article, we have talked about instance variables with the help of practical example. So, the instance variable can be used by any method or function inside a class as compared to static and local variables.

About the author

Muhammad Huzaifa

I am a computer science graduate with a passion to learn technical knowledge and share it
with the world. I love to work on top state-of-the-art computing languages. My aim is to best
serve the community with my work.