Static

The static keyword

The static keyword in Java is used for memory management. It allows defining:

  • Static variables

  • Static methods

  • Static blocks

  • Static nested classes

A static member belongs to the class, not instances of the class.

A common use is static variables that hold global values shared across all objects. For example, a counter tracking total objects created.

Static methods also don't require making an object. They belong to the class and can be called using ClassName.method() style.

Static variables

A static variable is shared by all instances of a class. It's memory is allocated when the class is loaded.

class Student {
    static String college = "Stanford";
    int rollNo;  
    String name;
}

Here, college is static as it's the same for all students.

Static methods

A static method belongs to the class. It can be invoked without creating an instance.

static int addNumbers(int a, int b) {
    return a + b;
}

⚡ Rules for Static in Java ⚡

The static keyword in Java indicates something is related to the class itself, rather than individual instances of the class. There are some key rules around using static.

📊 Rules for Static Variables 📊

  • Declared using static keyword

  • Belong to the class, rather than objects

  • A single copy exists that is shared across all objects

  • Accessible through the class name rather than objects

For example:

public class App {

  public static String name = "MyApp";

}

Only one copy of name exists even if multiple App objects are created.

⚙️ Rules for Static Methods ⚙️

  • Declared with static keyword

  • Can be called without creating an object

  • Cannot access non-static members directly

For example:

public class MathUtils {

  public static double sum(double a, double b) {
    return a + b;
  }

}

sum() is a utility method callable by MathUtils.sum(...) without instantiating MathUtils.

🧱 Rules for Static Blocks 🧱

  • Declared with static { }

  • Executed when class is first loaded

  • Used to initialize static variables

For example:

static {
  name = calculateName(); 
}

This initializes the static name when the class loads.

🏢 Rules for Static Nested Classes 🏢

  • Declared as static inside another class

  • Can access only static members of outer class

  • No reference to instance of outer class

For example:

public class Outer {
  
  static class Nested {
    //...
  }

}

So those are some key rules to follow for proper usage of static in Java.

Main method

The main() method must be static as JVM looks for a static method to start execution.

Last updated