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);
Sum of first 10 numbers -> 45
  • 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.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course