The keyword static is used to say that a variable or a method belongs to the class and not to the instance. We can also have static block of code and static nested class.
static things are shared across all instances.
The static variables are stored in the class area and are created at the time of class loading. So we can essentially have a code of block that can execute before the main method is called.
Even though static variables and methods belong to the class, we can use the static variables and methods through an instance.
public class Scope {
static {
System.out.println("I will be called before main.");
}
public static void main(String[] args) {
IAmGroot grootInstance = new IAmGroot();
System.out.println(IAmGroot.iAmAStaticVariable);
System.out.println(grootInstance.iAmAStaticVariable); // not preferred
IAmGroot.iAmAStaticMethod();
grootInstance.iAmAStaticMethod(); // not preferred
}
}
class IAmGroot {
static int iAmAStaticVariable = 0;
static void iAmAStaticMethod() {
System.out.println("iAmAStaticMethod");
}
}