The static keyword is used to create fields and methods that can be accessed without having to make an instance of the class. Static (class) members only exist in one copy, which belongs to the class itself, whereas instance (non-static) members are created as new copies for each new object. That means static methods can’t use instance members because these methods aren’t part of an instance. On the other hand, instance methods can use both static and instance members:
Accessing static members
To access a static member from outside the class, the class name is used followed by the dot operator. This operator is the same as the one used to access instance members, but to reach them an object reference is required. Trying to access a static member by using an object reference (instead of the class name) will result in a warning since this makes it more difficult to see that a static member is being used:
Static methods
The advantage of static members is that they can be used by other classes without having to create an instance of the class. Fields should therefore be declared static when only a single instance of the variable is needed. Methods should be declared static if they perform a generic function that’s independent of any instance variables. A good example of this is the Math class which contains only static methods and fields:
Math is one of the classes that’s included by default in every Java application, because it belongs to the java.lang package, which is always imported. This package contains classes fundamental to the Java language, such as String, Object, and System.
Static fields
Static fields have the advantage of persisting throughout the life of the application. That means they can be used, for example, to record the number of times a method has been called across all instances of the class. The initial value for a static field will only be set once, sometime before the class or field is ever used:
Static initialization blocks
A static initialization block can be used if the initialization of static fields requires more than one line or some other logic. This block, in contrast to the constructor, will only be run once, at the same time as the static fields are initialized:
Instance initialization blocks
An initialization block provides an alternative method for assigning instance fields. This block is placed on the class level, just like the static initialization block, but without the use of the static keyword. Any code placed between the brackets will be copied to the start of every constructor by the compiler:
A class can have multiple instance initialization and static initialization blocks.