static keyword in Java

🧠 What is static?

The static keyword in Java is used to indicate that a field, method, or block belongs to the class rather than to any specific object. It means it can be accessed without creating an object.


πŸ”Έ Uses of static:

  1. Static Variables – Shared across all objects.

  2. Static Methods – Can be called without an object.

  3. Static Blocks – Run only once when the class is loaded.


πŸ§ͺ Example:

class Student {
static String college = "ABC College"; // shared by all
String name;

Student(String n) {
name = n;
}

void display() {
System.out.println(name + " from " + college);
}
}

πŸ“ž Calling Static Method:

class Demo {
static void greet() {
System.out.println("Hello, World!");
}

public static void main(String[] args) {
Demo.greet(); // No object needed
}
}


πŸ“Œ Key Points:

  • Saves memory because shared members are loaded once.

  • Useful for utility methods.

  • Static methods can’t access non-static data directly.

Related Posts