Static Members in Java

Static members are class-level members β€” meaning they belong to the class itself, not to any specific object (instance) of the class. There are two types of static members:

1. Static Variables (Class Variables)

  • A static variable belongs to the class and is shared by all objects of that class.
  • It is initialized only once, when the class is first loaded into memory.
  • If one object changes the value of a static variable, all other objects see that updated value, since there is only one shared copy.
  • Static variables are useful for data that should be common to all instances, like a company name, or a counter to track how many objects were created.

2. Static Methods (Class Methods)

  • A static method belongs to the class rather than to any object.
  • It can be called without creating an object by using the class name.
  • Static methods can only access static variables and call other static methods.
  • They cannot access instance (non-static) variables or methods directly, because instance members belong to objects, not the class.
  • Static methods are often used for utility or helper functions that don’t depend on object data.

Code Snippet

//Static Members in Java

//Static Variables and Static Methods
class staticTest {
    static int a = 10;
    int b = 20;

    void show() {
        System.out.println("A : " + a + " B : " + b);
    }

    static void display() {
        System.out.println("A : " + a);
    }
}

public class App {
    public static void main(String args[]) {
        staticTest o1 = new staticTest();
        o1.show();
        staticTest o2 = new staticTest();
        o2.b = 100;
        staticTest.a = 200;
        o2.show();
        o1.show();
    }
}