DEV Community

Divya Divya
Divya Divya

Posted on

Static and Non-Static in Java?

Static :

A static variable is a variable declared with the static keyword inside a class.

  • It belongs to the class, not to any object.
  • Only one copy exists in memory, shared by all objects of the class.
  • Can be accessed using the class name without creating an object.

Example :

class Student {
    static int count = 0; // shared by all objects

    Student() {
        count++; // increases when new student is created
    }
}

public class Main {
    public static void main(String[] args) {
        new Student();
        new Student();
        System.out.println("Total students: " + Student.count); // 2
    }
}
Enter fullscreen mode Exit fullscreen mode

Why is use :

  • Shared Data: When the same value is needed for all objects.
  • Memory Efficiency: Only one copy exists in memory.
  • Class-Level Access: Can access without creating objects.
  • Consistent Value Across Objects: Any change affects all objects.
  • Utility Purposes: Counters, constants, or common data for the class.

Non-Static :

Non-Static refers to Object specific information.

  • Every object has its own copy.
  • Non-static variables or methods can be accessed only after creating an object.
  • In static → common for all objects (class-level),
  • in non-static → specific to each object (object-level).

Example :

class Student {
    String name; 

    void showName() {
        System.out.println(name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Divya";
        s1.showName(); 

        Student s2 = new Student();
        s2.name = "Aruna";
        s2.showName(); 
}
Enter fullscreen mode Exit fullscreen mode

Why is use :

  • Object-Specific Data: When each object needs its own separate values.
  • Example: name of each student.
  • Independent Behavior: Non-static methods can work with object-specific data.
  • Encapsulation: Helps store information specific to an object, not shared across all objects.

Top comments (0)