DEV Community

Hayes vincent
Hayes vincent

Posted on

Variable in java

1️⃣ Local Variable

Variable declared inside a method, constructor, or block

class LocalExample {
    void show() {
        int a = 10;   // local variable
        System.out.println(a);
    }

    public static void main(String[] args) {
        LocalExample obj = new LocalExample();
        obj.show();
    }
}
Enter fullscreen mode Exit fullscreen mode

Key points

Works only inside the method

Must be initialized before use

Memory created when method is called

2️⃣ Global Variable (Instance Variable)

Variable declared inside class but outside methods


class GlobalExample {
    int x = 20;   // global (instance) variable

    void display() {
        System.out.println(x);
    }

    public static void main(String[] args) {
        GlobalExample obj = new GlobalExample();
        obj.display();
    }
}

Enter fullscreen mode Exit fullscreen mode

Key points

Belongs to object

Default value given (0, null, false)

Access using object

3️⃣ Static Variable

Variable declared using static keyword
Shared by all objects

class StaticExample {
    static int count = 0;   // static variable

    StaticExample() {
        count++;
    }

    public static void main(String[] args) {
        new StaticExample();
        new StaticExample();
        new StaticExample();

        System.out.println(count);
    }
}


Output

3
Enter fullscreen mode Exit fullscreen mode

Key points

Only one copy in memory

Access using class name

Memory allocated once

4️⃣ Non-Static Variable

Normal instance variable (without static)

class NonStaticExample {
    int num = 5;   // non-static variable

    void show() {
        System.out.println(num);
    }

    public static void main(String[] args) {
        NonStaticExample obj1 = new NonStaticExample();
        NonStaticExample obj2 = new NonStaticExample();

        obj1.num = 10;

        obj1.show(); // 10
        obj2.show(); // 5
    }
}
Enter fullscreen mode Exit fullscreen mode

Key points

Each object has separate copy

Access using object

Different values for different objects

Top comments (0)