Instance Variables vs Local Variables in JAVA

Instance Variables:-

  • Variables that are declared in the global scope i.e. at class level.

  • By default, their values are initialized to default values depending on data types. For ex. for int data type, value is initialized to 0.

  • The memory for instance variables is allocated on heap at the time of object creation.

  •     public class Laptop {
            int ram;
            String brand;
            public void display() {
                System.out.println(brand+" laptop is having ram of "+ram+"gb");
            }
        }
    

Local Variables:-

  • Variables that are declared in the local scope i.e. at block level or method level or in the loops or conditional statements.

  • By default, their values are not initialized as instance variables. Hence their values needs to be initialized everytime we declare a local variable

  • The memory for instance variables is allocated at stack level.

  •     public class LocalVariable {
            public void doSomething() {
                int i = 10; 
        // this variable is declared inside method block and it has scope inside method only
                System.out.println(i);
            }
        }