Java Static Methods

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.  

public static void geek(String name)
{
 // code to be executed....
}
// Must have static modifier in their declaration.
// Return type can be int, float, String or user defined data type.

Memory Allocation of Static Methods

They are stored in the Permanent Generation space of heap as they are associated with the class in which they reside not to the objects of that class. But their local variables and the passed argument(s) to them are stored in the stack. Since they belong to the class, so they can be called to without creating the object of the class.

Important Points:  

  • Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName.methodName(args).
  • They are designed with the aim to be shared among all objects created from the same class.
  • Static methods can not be overridden, since they are resolved using static binding by the compiler at compile time. However, we can have the same name methods declared static in both superclass and subclass, but it will be called Method Hiding as the derived class method will hide the base class method.

Below is the illustration of accessing the static methods: 

Java




// Example to illustrate Accessing
// the Static method(s) of the class.
import java.io.*;
 
class Geek {
 
    public static String geekName = "";
 
    public static void geek(String name)
    {
        geekName = name;
    }
}
 
class GFG {
    public static void main(String[] args)
    {
 
        // Accessing the static method geek()
        // and field by class name itself.
        Geek.geek("vaibhav");
        System.out.println(Geek.geekName);
 
        // Accessing the static method geek()
        // by using Object's reference.
        Geek obj = new Geek();
        obj.geek("mohit");
        System.out.println(obj.geekName);
    }
}


Output

vaibhav
mohit

Note:

Static variables and their values (primitives or references) defined in the class are stored in PermGen space of memory. 

Static methods vs Instance methods in Java

In this article, we are going to learn about Static Methods and Instance Methods in Java.

Similar Reads

Java Instance Methods

Instance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the method is defined....

Java Static Methods

...

Frequently Asked Questions

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class....