What Is Static in Java?

What Does Static Mean in Java?

In the Java programming language, the keyword static means that the particular member belongs to a type itself, rather than to an instance of that type. This means we’ll create only one instance of that static member that’s shared across all instances of the class. We can apply the keyword to variables, methods, blocks, and nested classes.

Why Do We Use Static Methods in Java?

The main purpose of using the static keyword in Java is to save memory. When we create a variable in a class that will be accessed by other classes, we must first create an instance of the class and then assign a new value to each variable instance – even if the value of the new variables are supposed to be the same across all new classes/objects.

How to Create a Static Variable in Java

Static methods have access to class variables (static variables) without using the class’s object (instance). Only static data may be accessed by a static method. It is unable to access data that is not static (instance variables).

Accessing Static Methods in Java

We can call or access a static method directly using the class name, followed by dot (.) operator and method name. The general syntax to call a static method in Java is as follows: className.methodName(); // Here, className is the name of a class and methodName is name of method.

Static Method in Java

To declare a static method in a program, use a static keyword before the method’s return type. The general syntax to declare the static method (or class method) in Java is as follows:

java
Access_modifier static void methodName() {
// Method body
}

Leave a Comment