Static keyword in Java

In Java, static is a keyword that can be used with variables, methods, and nested classes to create class-level or static members. Static members belong to the class itself, rather than to any instance of the class. This means that they can be accessed using the class name, without creating an object of the class.


Static variables, also called class variables, are variables that belong to the class and are shared by all instances of the class. They are declared using the static keyword and can be accessed using the class name followed by the variable name. For example:


public class MyClass {
    static int x = 5;

    public static void main(String[] args) {
        System.out.println(MyClass.x); // Outputs 5
    }
}


In this example, x is a static variable declared inside the MyClass class. It can be accessed using the class name MyClass.x from the main method, without creating an instance of the class.


Static methods, also called class methods, are methods that belong to the class and can be called using the class name, without creating an object of the class. They are declared using the static keyword and can only access other static members of the class. For example:


public class MyClass {
    static void myStaticMethod() {
        System.out.println("Static method");
    }

    public static void main(String[] args) {
        MyClass.myStaticMethod(); // Outputs "Static method"
    }
}


In this example, myStaticMethod() is a static method declared inside the MyClass class. It can be called using the class name MyClass.myStaticMethod() from the main method, without creating an instance of the class.


Static nested classes are nested classes that are declared with the static keyword. They can be accessed using the outer class name, without creating an instance of the outer class. For example:


public class OuterClass {
    static class NestedClass {
        public void myMethod() {
            System.out.println("Static nested class");
        }
    }

    public static void main(String[] args) {
        OuterClass.NestedClass obj = new OuterClass.NestedClass();
        obj.myMethod(); // Outputs "Static nested class"
    }
}


In this example, NestedClass is a static nested class declared inside the OuterClass class. It can be accessed using the outer class name OuterClass.NestedClass and instantiated using new OuterClass.NestedClass().


In summary, the static keyword in Java is used to create class-level or static members that belong to the class itself, rather than to any instance of the class. They can be accessed using the class name, without creating an object of the class.