Types of Variables

Manmohan WableManmohan Wable
1 min read

Instance:- If the value of a variable is changing from an object to an object then it is called an instance variable

eg:-


class Employee {
    void getEmployee () {
        int x = 10; //not an instance variable
    }

    static {
        int x = 10; //not an instance variable
    }

    Employee () {
        int x = 10; //not an instance variable
    }
};
  • Instance variable should be declared directly into the class but outside any method or block.

  • The instance variable will be created in heap memory.


class Employee {
    string name;
    int id;

    public static void main() {
        System.out.println(name);
    }
};

Error:- Non-static context cannot be accessed from static context

class X {
    int y = 10;

    public static void main() {
        X x = new X();
    }

    void m1() {
        System.out.println(y);
    }
}

Here, m1 is a method of an instance of a class that is non-static and can be call non-static variables

class X {
    public static void main() {
        int x;
        system.out.println(x);
    }
};

Error:- variable x not initialized

NOTE:- JVM provides default values to instance variables

0
Subscribe to my newsletter

Read articles from Manmohan Wable directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manmohan Wable
Manmohan Wable