Table of contents
1.
Introduction
2.
Features of static method
3.
Syntax to declare a static method
4.
Syntax to call a static method
5.
Why Use Static Methods?
6.
Restrictions of Static Method in Java
7.
Why is the main Method in Java Static?
8.
Important Points to Remember about Static Methods
9.
Difference between the Static Method and Instance Method
10.
Frequently Asked Questions
10.1.
Can a static method be overloaded?
10.2.
Can a static method be synchronized?
10.3.
Can a static method be final?
11.
Conclusion 
Last Updated: Oct 15, 2024
Easy

Static Method in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, a static method is a special type of method that belongs to the class rather than an instance of the class. This means that you don't need to create an object of the class to use these methods. Static methods are useful for performing operations that don't require access to instance variables or methods. It can be called without creating an object of the class. Static methods are common in many Java programs where operations need to be accessed globally rather than requiring an object to invoke them. 

Static Method in Java

In this article, we will discuss the features, syntax, & usage of static methods in Java. We will also understand the restrictions & differences between static & instance methods. 

Features of static method

Static methods in Java have many important features that distinguish them from instance methods:

1. They belong to the class itself rather than instances of the class. 
 

2. They can be called directly on the class without creating an object.
 

3. They can only access static members (variables & methods) of the class directly.
 

4. They cannot use the "this" keyword as there is no instance associated with static methods.
 

5. They are often used for utility functions or operations that don't require a state.

Syntax to declare a static method

To declare a static method in Java, you need to use the "static" keyword before the method's return type.

The syntax is : 

modifier static returnType methodName(parameter list) {
   // method body
}

Let's understand the components in syntax:

  • `Modifier`: Optional access modifiers such as public, private, or protected.
     
  • `static`: The keyword that makes the method static.
     
  • `returnType`: The data type of the value returned by the method (e.g., void, int, String).
     
  • `methodName`: The name of the method.
     
  • `parameter list`: The list of parameters the method accepts, enclosed in parentheses.


Let’s see an example of declaring a static method that calculates the sum of two integers:

public static int sum(int a, int b) {
   return a + b;
}


In this example, the `sum` method is declared as `public` (accessible from anywhere), `static` (belongs to the class), & takes two `int` parameters `a` & `b`. It returns the sum of `a` & `b`.

Syntax to call a static method

To call a static method in Java, you use the class name followed by the method name, separated by a dot (.). The syntax is :

ClassName.methodName(arguments);


In this syntax:

  • `ClassName`: The name of the class where the static method is defined.
     
  • `methodName`: The name of the static method you want to call.
     
  • `arguments`: The values or variables passed to the method as arguments, if any.


Let’s see an example of calling the `sum` static method we declared earlier:

int result = MyClass.sum(5, 3);
System.out.println("Sum: " + result); // Output: Sum: 8


In this example, we call the `sum` method directly on the class `MyClass` (assuming that's where the method is defined) & pass the arguments `5` & `3`. The returned value is stored in the `result` variable, which is then printed.

Note: Always remember that you don't need to create an instance of the class to call a static method. You can invoke it directly on the class itself.

Why Use Static Methods?

The important reasons for which the Static method is useful are : 
 

1. Utility Functions: Static methods are often used to create utility functions that perform common tasks or calculations. These methods don't require any object state & can be called independently.
 

2. Code Organization: Static methods help organize related functionality within a class. They allow you to group methods that belong together logically, making the code more modular & easier to understand.
 

3. Performance: Calling a static method is slightly faster than calling an instance method because it doesn't require creating an object of the class. This can provide a small performance boost, especially when the method is called frequently.
 

4. Accessing Static Members: Static methods can directly access & manipulate static variables of the class. This is useful when you need to perform operations on shared class-level data.
 

5. Factory Methods: Static methods are commonly used as factory methods to create & return instances of a class. They encapsulate the object creation logic & provide a convenient way to create objects without using the `new` keyword directly.
 

6. Singleton Pattern: Static methods are often used in the implementation of the Singleton pattern, where a class has only one instance. The static method ensures that only one instance of the class is created & provides a global access point to that instance.

Restrictions of Static Method in Java

Just like every other important feature, the static method also has their limitations, like : 
 

1. Cannot Access Non-Static Members: Static methods can only directly access other static members (variables & methods) of the class. They cannot directly access non-static (instance) variables or methods. To access non-static members, you need to create an instance of the class.
 

2. No Usage of `this` Keyword: Static methods cannot use the `this` keyword because `this` refers to the current instance of the class. Since static methods belong to the class itself & not to any specific instance, using `this` inside a static method will result in a compilation error.
 

3. Cannot be Overridden: Static methods cannot be overridden in subclasses. If a subclass defines a method with the same name & signature as a static method in the superclass, it will hide the superclass method instead of overriding it. This can lead to confusion & unexpected behavior.
 

4. Cannot be Abstract: Static methods cannot be declared as abstract. Abstract methods are meant to be overridden in subclasses, but static methods cannot be overridden. Therefore, declaring a static method as abstract will result in a compilation error.
 

5. Limited Access to Object State: Since static methods don't have access to object state (non-static members), they are limited in their ability to operate on instance-specific data. If a static method needs to work with instance data, it typically requires the data to be passed as parameters.

Why is the main Method in Java Static?

In Java, the `main` method is declared as `static` because it serves as the entry point of a Java program. When you run a Java program, the Java Virtual Machine (JVM) looks for the `main` method to start the execution. Let’s discuss a few reasons why the `main` method is declared as `static`:
 

1. No Object Creation Required: By making the `main` method static, it allows the JVM to call the method without creating an instance of the class. The JVM can directly invoke the `main` method without the need for object instantiation.
 

2. Single Entry Point: The `static` nature of the `main` method ensures that there is a single entry point for the program. It provides a consistent and standardized way to start the execution of a Java application.
 

3. Independence from Object State: The `main` method is responsible for starting the program & coordinating the flow of execution. It shouldn't depend on the state of any particular object. By being static, the `main` method can perform its tasks independently, without relying on instance-specific data.
 

4. Command-Line Arguments: The `main` method typically accepts command-line arguments, which are passed as an array of strings (`String[] args`). These arguments are not associated with any specific object instance, so a static method is appropriate to handle them.

 

5. Convention and Consistency: Declaring the `main` method as `static` is a convention followed by Java programmers. It provides consistency across different Java programs & allows the JVM to easily identify & execute the entry point of the application.

Important Points to Remember about Static Methods

Let’s discuss some of the important points we need to remember while working with static methods in Java:

1. Naming Convention: It is a good practice to follow the Java naming convention for static methods. Method names should start with a lowercase letter, & if the name consists of multiple words, subsequent words should start with an uppercase letter (camelCase).
 

2. Accessibility: Static methods can have different access modifiers such as `public`, `private`, `protected`, or default (no modifier). Choose the appropriate access modifier based on the intended visibility & usage of the method.
 

3. Overloading: Static methods can be overloaded, which means you can define multiple static methods with the same name but different parameter lists within the same class. The compiler distinguishes between overloaded methods based on the number, type, & order of parameters.
 

4. Static Imports: Java allows you to import static members of a class using the `static` keyword in the import statement. This enables you to call static methods directly without specifying the class name. However, use static imports judiciously to avoid naming conflicts & maintain code readability.
 

5. Static Method Chaining: Static methods can be chained together, meaning you can call a static method on the result of another static method. This can lead to more concise & readable code, especially when working with utility classes or fluent APIs.
 

6. Avoid Excessive Static Methods: While static methods have their uses, it's important not to overuse them. If a method relies heavily on an instance state or needs to be overridden in subclasses, it should be an instance method instead of a static method.
 

7. Static Methods in Interfaces: Starting from Java 8, interfaces can contain static methods. These methods provide a convenient way to define utility methods related to the interface without requiring an implementation class.

Difference between the Static Method and Instance Method

Static MethodInstance Method
A static method belongs to the class itself and is associated with the class rather than instances of the class.An instance method belongs to instances of the class and is tied to specific objects created from the class.
A static method can be called directly on the class without the need to create an instance of the class.An instance method requires an instance of the class to be created before it can be called on that instance.
A static method can only directly access other static members (variables and methods) of the class. It cannot directly access non-static (instance) members.An instance method can access both static and non-static (instance) members of the class, allowing it to work with instance-specific data.
A static method cannot use this keyword because it doesn't have a reference to a specific instance of the class.An instance method can use this keyword to refer to the current instance of the class on which it is called.
A static method cannot be overridden in subclasses. If a subclass defines a method with the same name and signature as a static method in the superclass, it will hide the superclass method.An instance method can be overridden in subclasses, allowing subclasses to provide their own implementation of the method.
A static method cannot be declared as abstract because abstract methods are meant to be overridden in subclasses, and static methods cannot be overridden.An instance method can be declared as abstract, requiring subclasses to provide an implementation for the method.
A static method is accessed using the class name followed by the method name, such as ClassName.methodName().An instance method is accessed using an object reference followed by the method name, such as objectReference.methodName().
Static methods are often used for utility functions or operations that don't require access to instance-specific data. They are commonly used for tasks that are independent of object state.Instance methods are used for operations that depend on the state of an object. They can access and manipulate instance variables and perform actions specific to each object instance.

Frequently Asked Questions

Can a static method be overloaded?

Yes, a static method can be overloaded in Java. Overloading allows multiple static methods with the same name but different parameter lists to exist within the same class.

Can a static method be synchronized?

Yes, a static method can be declared as synchronized in Java. Synchronizing a static method ensures that only one thread can execute the method at a time, providing thread safety for shared class-level resources.

Can a static method be final?

Yes, a static method can be declared as final in Java. Making a static method final prevents it from being overridden in subclasses, ensuring that the implementation remains constant across the class hierarchy.

Conclusion 

In this article, we have learned about static methods in Java. We explained the features of static methods, like their association with the class itself, the ability to be called without creating objects, and their access to static members. We also discussed the syntax for declaring and calling static methods, highlighting the use of the static keyword and the class name. Additionally, we looked into the reasons for using static methods, like creating utility functions, organizing code, and improving performance. Apart from all this, we also looked at the limitations of this method and lastly, the difference between static and instance methods.

You can also check out our other blogs on Code360.

Live masterclass