DEV Community

Kanishka Shrivastava
Kanishka Shrivastava

Posted on

#java #oop #programming

Java Concepts I’m Mastering – Part 2: Static vs Instance Variables

Continuing my journey of mastering Java fundamentals while building real projects.

Today’s concept: Static vs Instance Variables

This concept seems basic — but it changes how you design classes.

Instance Variable

Belongs to an object

Each object gets its own copy

class Student {
    String name;   
}

Enter fullscreen mode Exit fullscreen mode

Every Student object will have its own name.

Static Variable

Belongs to the class

Shared among all objects

class Student {
    static String college = "RGPV";  
}

Enter fullscreen mode Exit fullscreen mode

All students share the same college.

Example:

class Student {
    String name;
    static String college = "RGPV";

    Student(String name) {
        this.name = name;
    }
}

Enter fullscreen mode Exit fullscreen mode

If 100 students are created:

100 different name values

Only 1 shared college

Memory-efficient and logically correct.

What I Learned

Use instance variables for object-specific data

Use static variables for shared data

Static members can be accessed without creating an object

Understanding this helps write cleaner and more structured code.

Next in the series: The this Keyword in Java.

Top comments (0)