The difference between instance and local variables in Java

Instance variables are declared inside a class but not within a method.
For example:
class Employee {

    // instance variable employee id
    public int id;

    // instance variable employee name
    public String empName;

    // instance variable employee age
    public int age;
}

Local variables are declared within a method.
For example:
In the following example, the sum local variable declared and initialized within a method:
package net.javaguides.corejava.variables;

public class LocalVariableExample {
    public int sum(int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum = sum + i;
        }
        return sum;
    }

    public static void main(String[] args) {
        LocalVariableExample localVariableExample = new LocalVariableExample();
        int sum = localVariableExample.sum(10);
        System.out.println("Sum of first 10 numbers -> " + sum);
    }
}
Output:
Sum of first 10 numbers -> 45
Note:
  • Local variables MUST be initialized before use!
  • Local variables do NOT get a default value! The compiler complains if you try to use a local variable before the variable is initialized.
Read more at https://www.javaguides.net/2018/10/variables-in-java-local-variable-class-variable-instance-variable.html

Comments