DEV Community

Bala Murugan
Bala Murugan

Posted on

Static and NOn-static

static variable :

*A static Variable belongs to the class, not to an object.

  • nly one copy is created and shared by all objects.

Example:

class Student {

    static String college = "Bala";
}

public class Main {

    public static void main(String[] args) {

        Student s1 = new Student();
        Student s2 = new Student();

        System.out.println(s1.college);
        System.out.println(s2.college);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Bala
Bala
Enter fullscreen mode Exit fullscreen mode

Non-Static Variable (Instance Variable):

A non-static variable belongs to an object.

Every object gets its own copy of the variable.

Example:

class Student {

    String name;
}

public class Main {

    public static void main(String[] args) {

        Student s1 = new Student();
        Student s2 = new Student();

        s1.name = "Bala";
        s2.name = "Kumar";

        System.out.println(s1.name);
        System.out.println(s2.name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Bala
Kumar
Enter fullscreen mode Exit fullscreen mode

Explanation:

s1 → name = Bala
s2 → name = Kumar

Each object has a separate copy of name.

Key Differences:

Static Variable Non-Static Variable
Belongs to class Belongs to object
One copy only Separate copy for each object
Shared by all objects Not shared
Access using class name Access using object

Top comments (0)