What Is the Static Keyword in Java?

The term "static" in Java serves as a Non Access Modifier, indicating that a field, method, block, or nested class is associated with the type itself rather than any specific instance of the type. This distinction emphasizes the behavior or characteristic of the entity in question in relation to the entire class rather than individual instances.

When a member (field, method, block, or nested class) is declared as static, it implies that it is not tied to a specific object or instance of the class. Instead, it exists as a single entity shared by all instances of the class. The behavior or state represented by the static member remains consistent across all instances, allowing for a unified and class-wide representation.

For instance, a static field in a class would possess the same value across all instances, as any modification to the static field would be reflected universally. Similarly, a static method can be invoked without the need for object instantiation, as it pertains to the class itself and does not rely on any specific instance.

The Static keyword can be applied to:

  1. Static Method
  2. Static Variable
  3. Initialization Block
  4. Nested class

Java Static Method

In Java, static methods can be called without creating an object of the class.

In normal case we call a method from the instance of that class.

Example
public class TestClass { public static void main(String[] args) { TestClass tc = new TestClass();//create a class instance tc.ShowMessage(); //call method using instance } void ShowMessage() { System.out.println("Here is the message"); } }

When we create a static method inside a class, methods can be called without creating an object of class.

Example
public class TestClass { public static void main(String[] args) { ShowMessage(); //calling without creting instance } static void ShowMessage() { System.out.println("Here is the message using static"); } }

In Java, a static method is limited to accessing only the static variables of a class and invoking solely the static methods of the class. Typically, static methods serve as utility methods intended for external usage by other classes without the requirement of instantiating an object. These class methods often serve as globally accessible functions within Java programs, providing functionality that transcends specific instances. An illustrative example of class methods is found in the java.lang.Math package, where they play a prominent role. As static methods do not pertain to any particular instance, they are unable to reference instance members; they can solely refer to other static members.

Features of static method

  1. A static method is a method which belongs to the class and not to the instance(object)
  2. A static method can be invoked without the need for creating an instance of a class
  3. A static method can call only other static methods and cannot call a non-static method from it
  4. A static method can access static data member and can change the value of it
  5. A static method cannot refer to this or super keywords in anyway

Java Static variable

A static variable in Java is associated with the class itself rather than any specific instance (object) of that class. It is initialized only once at the beginning of the program's execution and remains unchanged throughout its runtime. This single instance is shared among all instances of the class, and it can be accessed directly using the class name without the need for an object reference. One common application of static variables is to define constant values that are inherent to the class.

For instance, consider the declaration of a static variable: private static int stc = 0;. If this variable is incremented (stc++) in one instance of the class, the change will be reflected across all instances. Consequently, the value of stc will become 1 in all instances, demonstrating the shared nature of static variables.

By utilizing static variables, developers can establish class-level data that is accessible globally and consistent across all instances. This enables the storage of information that pertains to the class as a whole rather than individual objects.

Initialization Block

The static initializer in Java is a block of code denoted by the static {} construct within a class. This code block is executed only once, prior to the invocation of the class's constructor or main method. It serves as a class initializer, responsible for performing any necessary setup or initialization tasks specific to the class itself.

The static initializer block is denoted by the keyword static, indicating that it pertains to the class as a whole rather than any specific instance. This allows it to initialize static variables or perform other operations that are independent of object creation.

It is important to note that the static initializer block is executed in the order they appear in the class, ensuring proper sequencing of initialization tasks. This block is typically used to initialize static variables, set up static data structures, or perform any other one-time initialization steps required by the class.

In contrast, an instance initializer block is similar in structure but does not have the static modifier. It is executed when an instance of the class is created, before the constructor is called. Instance initializer blocks are useful when there is shared initialization logic required by multiple constructors of the class.

public class TestClass { static { System.out.println("Hello before main"); } }

It's automatically invoked when the class is loaded. A static block executes once in the life cycle of any program, and there's no other way to invoke it

From Java 7 , however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

Main class should contain method: public static void main (String[] args).

Nested class

Nested classes are classified into two categories: static and non-static. When a nested class is declared with the static modifier, it is known as a static nested class.

A static nested class is a nested class that exists independently of any instance of the enclosing class. It is essentially a top-level class that is nested within another class for organizational purposes. Unlike non-static nested classes (also known as inner classes), a static nested class does not have direct access to the instance variables and methods of the enclosing class.

Static nested classes are typically used when there is a logical relationship between the nested class and the enclosing class, but the nested class does not require access to the instance-specific members of the enclosing class. They provide a way to logically group classes together, enhancing code organization and encapsulation.

To use a static nested class, you can access it using the enclosing class name, followed by the nested class name. For example, if a class named Outer contains a static nested class named Nested, you can instantiate Nested using the following syntax: Outer.Nested nestedObject = new Outer.Nested();

Static nested classes have their own separate namespace and can contain static members, such as static fields, static methods, and static nested classes of their own. They can be accessed independently without requiring an instance of the enclosing class.

Example
public class OuterClass { public static class StaticNestedClass { } public class NonStaticNestedClass { } }

In order to create an object for the static nested class, use the following syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

The key difference between them, you can't create an NonStaticNestedClass instance without an OuterClass whereas you can create an StaticNestedClass object independently.

Conclusion

The static keyword in Java is used to define class-level members that are associated with the class itself rather than individual instances, allowing them to be accessed without the need for object instantiation.