Last Updated:

What is static in Java? - Static methods, variables; static block and Java class

Static is a keyword in Java. We cannot create a class or package name with a static key. In Java, static can be used in four cases:

1. Static variables

In Java, we can use the static keyword in a class-level variable. A static variable of the class and does not belong to the object/instance of the class. For example, static variables are common to all instances of an object and are not thread-safe. Typically, static variables are used with the final keyword for shared resources or constants that can be used by all objects. If the static variable is not private, then we can access it in the following way: ClassName. VARIABLENAME

2. Java static methods. Like static variables, static methods belong to the class, not to instances of the class. A static method can access only static class variables and call only static methods of the class. Typically, static methods are utility (helper) methods that must be used by other classes without the need to create an instance. The main() method is the entry point to any JAVA program—it is static.

It is interesting to know that starting with Java 8, we can also use static methods in interfaces.

3. Static block in Java: A static block with a group of statements is used to initialize static class variables. It is primarily used to create static resources when a class is loaded. We can't access non-static variables in a static block. We can have a few static blocks in a class, although that doesn't make much sense. A static block of code runs only once, when a class is loaded into memory.

4. Static class in Java: We can use the static keyword with nested classes. The static keyword cannot be used with top-level classes. A static nested class is the same as any other top-level class, only nested for easy packaging.

Let's look at all the use cases for the static keyword on the example of a Java program.

StaticExample.java

Let's see how to use static variables, classes, and methods in your program.

TestStatic.java

The result of this program: