Sobes.tech
Junior

What does the 'static' keyword mean in Java?

sobes.tech AI

Answer from AI

static in Java is used to declare elements that belong to the class rather than a specific instance of an object.

The keyword can be applied to:

  • Variables (fields):
    • One copy of the variable exists for the entire class, regardless of how many instances are created.
    • It can be accessed through the class name (e.g., ClassName.staticVariable).
    // Example of a static variable
    public class MyMath {
        public static final double PI = 3.14159;
        // Access: MyMath.PI
    }
    
  • Methods:
    • The method belongs to the class, not a specific object.
    • It can be called using the class name (e.g., ClassName.staticMethod()).
    • It does not have access to non-static members of the class (variables or methods), as they are tied to an instance.
    // Example of a static method
    public class Calculator {
        public static int add(int a, int b) {
            return a + b;
        }
        // Call: Calculator.add(5, 3)
    }
    
  • Initialization blocks:
    • Executed once when the class is loaded into the JVM.
    • Used for initializing static fields or performing other class-related actions.
    // Example of a static block
    public class DataInitializer {
        static {
            // Code executed when the class is loaded
            System.out.println("DataInitializer class loaded.");
        }
    }
    
  • Inner/nested classes:
    • A static nested class behaves like a regular top-level class, except that it is inside another class.
    • Does not require an instance of the outer class to access it.
    • Has access only to static members of the outer class.
    // Example of a static nested class
    public class OuterClass {
        static class StaticInnerClass {
            // Fields and methods of the static nested class
        }
    }
    // Access: OuterClass.StaticInnerClass inner = new OuterClass.StaticInnerClass();
    

Using static helps in creating utility classes, storing common data, and managing state at the class level.

What does the 'static' keyword mean in Java? — Java - sobes.tech