Static Method in Java (with Examples)

When a method is declared with the keyword static in its heading, it is called a static method in Java. If not, it is called non-static (or instance) method. A static method is also known as class method because, like a static variable, it is also tied to the class itself, not to an object (instance) of the class.

Since a static method belongs to the class itself rather than to any specific instance, we can call and execute it directly using the class name without creating an object of class.

We frequently use static methods in Java program. The most common example of static method is the main() method, which contains the static keyword in its definition and acts as the entry point of any program.

Java standard libraries extensively contain numerous static methods to perform various operations. For example, the Math class contains several static methods such as Math.sqrt(), Math.pow(), and Math.random() to perform mathematical tasks.

Static methods generally have better performance compared to instance methods in certain scenarios. Since we do not need for object creation, they can be more efficient in terms of memory and execution speed.

Java 8 also allows us to define static methods in an interface that works exactly the same as static methods in the class. They must be called using interface name.

Syntax to Declare Static Method in Java


To declare a static method in Java program, use the static keyword before the method’s return type. The term static means that the method belongs to the class rather than to any specific instance (object) of the class. Therefore, a static method can be called without creating an object of the class.

The general syntax to declare a static method ( or class method) in Java is as follows:

access_modifier static return_type methodName(parameters)
{ // block start
  // Method body. 
} // block end.

For example:

public static void displayMessage() {
     System.out.println("Hello, this is a static method.");
}

In the figure below, we have defined various forms of static methods with or without return type. This will give a clearer view of how to define static methods in different ways.
Various types of static method declaration in Java

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.

For example:
    Student.add(); // Student is the name of class and add is a method name.

Key Features of Static Method (Class Method) in Java


There are several key features of a static method in Java that you should keep in mind. They are as follows:

1. A static method in a class can directly access other static members of the class. We do not need to create an object of class for accessing other static members. It can be called directly within the same class and outside the class using the class name.

2. A static method cannot access instance (non-static) members of a class directly because it does not belong to any specific object — it belongs to the class itself. However, a static method can access instance members indirectly by using an object reference. The relationship between instance and static members are summarized in the below figure:

Relationship between instance and static members in Java

From the figure, it is clear that:

  • An instance method can call both instance and static methods. It can also access instance and static data variables. This is because instance methods are tied to an object, and every object has access to both types of members.
  • A static method can call only static methods directly. It can also directly access a static data variable inside the static method.
  • Static method cannot directly access instance methods or instance variables because it is not tied to any object. However, it can access them indirectly using an object reference.

3. We cannot declare a static method and an instance method with the same signature in the same class hierarchy. This would cause a compile-time error due to method signature conflict.

4. When we create a static method in the class, only one copy of the static method is created in the memory and shared across all objects of the class. No matter you create 100 objects or 1 object, the static method is stored only once in the memory. All objects share the same method.

5. A static method in Java is also loaded into the memory before the object creation. During class loading, static methods and variables are initialized and placed in memory.

6. The static method is always bound with compile time (early binding).

7. Since static methods do not operate on an instance, they cannot refer to this or super keywords in any way.

8. Static methods can be overloaded in Java but cannot be overridden because they are bound with class, not instance.

9. Static methods and other static members are stored in the “Method Area” (also called Class Area), not in heap or stack. In prior to Java 8, this area was called PermGen (Permanent Generation). In Java 8 and later, it is replaced by Metaspace, which grows dynamically.

Why Instance Variable is not Available to Static Method?


When a Java class is first referenced — either by calling a static method like main() method, accessing a static variable, or creating an object using new keyword, the JVM loads the .class file into memory.

During this class loading and initialization phase, all static members (i.e., static variables, static blocks, and static methods) are initialized and executed in the order they appear in the source code. This process happens only once during class loading.

When we declare a static method in a Java program, the JVM executes static methods first, even before an object of the class is created. Since instance variables belong to objects, and no objects exist yet at the time of the execution of static method, the static method cannot access instance variables directly. Therefore, a static method can only access instance variables through an object reference, if an object has been explicitly created.

Access to Instance and Static Variables from Static and Instance Methods

Example 1: Let’s take a simple Java program to test whether a static method can access an instance variable and static variable or not. In this program, we will define:

  • An instance variable y
  • A static variable x
  • Instance method display()
  • Static method show()

We will then try to read and print both variables from both methods to understand the behavior.

package staticMethod; 
public class StaticTest 
{ 
 // Instance Area. 
    static int x = 20; // Static variable 
    int y = 30; // Instance variable 

 // Declare an instance method. 
    void display() 
    { 
   // This is an instance area. So, we can directly call instance variable without using object reference variable.
   // Because the method is tied to an object and this is available.
   // Since we can also access static members from an instance method, we can directly call static variable as well. 
      System.out.println(x); 
      System.out.println(y); 
    } 

 // Declare a static method. 
    static void show() 
    { 
   // This is a static area. So, we can call static variable directly inside static method.
      System.out.println(x);

   // This commenting statement will generate compile time error because we cannot access an instance variable inside static method. 
   // System.out.println(y);  
   } 

public static void main(String[] args) 
{ 
 // Create the object of the class. 
    StaticTest st = new StaticTest(); 
 
 // Call instance method using reference variable st. 
    st.display(); 

 // Call static method. 
     show(); 
   } 
}
Output: 
       20 
       30 
       20

Calling a Static Method Using a Null Reference in Java


An interesting feature of Java is that you can also access static methods using a nullable reference as:

StaticMethod s1 = null; // Nullable reference
s1.show(); // No NullPointerException

The static method will still execute correctly because static methods are resolved at compile time based on the class, not the object. When you call s1.show(), even though s1 is null, the compiler translates it to StaticMethod.show(). Since no actual instance method is being called, no NullPointerException is thrown.

Example 2:

package staticMethod; 
public class StaticMethod 
{ 
  static int a = 10; // static variable.
  void display() 
  { 
     System.out.println("This is an instance method"); 
  } 
  static void show()
  { 
     System.out.println("This is a Static method"); 
  } 

  public static void main(String[] args) 
  { 
    StaticMethod sm = new StaticMethod(); 
    sm.display(); 
    StaticMethod s = null; 
    s.show(); 
    int c = s.a; 
    System.out.println(c); 
  } 
}
Output: 
        This is an Instance method 
        This is a Static method 
        10

While this is legal, but it’s not recommended for readability and best practices. You should always use the class name (StaticMethod.show()) instead of a null reference.

How to Change Value of Static Variable Inside Static Method?


In Java, a static method allow us to access a static variable and can also change its value. Let’s take an example program where we will change the value of static variable inside static method. Look at the following program code.


Example 3:

package staticMethod; 
public class ValueChange 
{ 
  static int a = 10; 
  static int change() 
  { 
     int a = 20; 
     return a; 
  } 
  public static void main(String[] args) 
  { 
 // Call static method using the class name. 
 // Since it will return an integer value, so we will store it into a variable named changeValue of type int. 
    int changeValue = ValueChange.change(); 
    System.out.println(changeValue); 
  } 
}
Output: 
       20

Example 4: Let’s write a Java program to calculate the square and cube of a given number by using static method.

package staticMethod; 
public class SquareAndCube 
{ 
  static int x = 15;  
  static int y = 20; 

  static int square(int x) { // Here, x is a local variable. 
     int a = x * x; 
     return a; 
  } 
  static int cube(int y) { // Here, y is a local variable. 
    int b = y * y * y; 
    return b; 
  } 
  public static void main(String[] args) 
  { 
    int sq = square(5); 
    int CB = cube(10); 
    System.out.println(sq); 
    System.out.println(cb); 
  } 
}
Output: 
       25 
       1000

Can We Use this or super Keyword in Class Method in Java?


In entire Java, “this and “super” keywords are not allowed inside the static method or any static context. We cannot use “this” keyword in the body of static method because static methods are associated with a class, not to any specific instance. As a result, this keyword which refers to the current object is not available in static methods.

Only instance methods have an implicit “this” object reference associated with them. Static methods do not have a “this” object reference associated with them.

Similarly, we cannot use the super keyword inside the body of static method. This is because we use super keyword to call superclass method from the overriding method in the subclass. Since we cannot override the static methods, we cannot use the super keyword in its body. Let’s take an example program based on it.

Example 5:

package staticMethod; 
public class ThisTest 
{ 
 // Declare instance variables. 
    int x = 10; 
    int y = 20; 

 // Declare a static method with two parameters x and y of type int. 
    static void add(int x, int y) 
    { 
       System.out.println(this.x + this.y); // Compile time error. 
    } 

    public static void main(String[] args) 
    { 
       ThisTest.add(20, 30); 
    } 
}
Output: 
       Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
       Cannot use this in a static context Cannot use this in a static context

Calling Static Method from Another Class


We can call a static method in Java from another class directly using the class name, without creating an object of that class. Let’s understand it with help of an example program. In this example, we will create a class Student and declare three static methods, such as name(), rollNo(), and std(), each returning a value.

Example 6:

package staticVariable; 
class Student 
{ 
   static String name(String n) 
   { 
     return n; 
   } 
  static int rollNo(int r) 
  { 
     return r; 
  } 
  static int std(int s) 
  { 
     return s; 
  } 
}

Now create another class StudentTest and call static method with passing argument values.

public class StudentTest { 
public static void main(String[] args) 
{ 
 // Call static method using class name and pass the string argument. 
 // Since it will return string value, so we will store it into a variable named nameStudent of type string. 
    String nameStudent = Student.name("Shubh"); 

 // Call and pass the integer value. 
 // Since it will return an integer value, so we will store it into a rollStudent and std variables of type int. 
    int rollStudent = Student.rollNo(5); 
    int std = Student.std(8); 
    
    System.out.println("Name of Student: " +nameStudent); 
    System.out.println("Roll no. of Student: " +rollStudent); 
    System.out.println("Standard: " +std); 
  } 
}
Output: 
       Name of Student: Shubh 
       Roll no. of Student: 5 
       Standard: 8

Calculating Factorial Series Using a Static Method

Example 7: Let’s write a Java program to calculate the factorial series using a static method in Java.

package staticVariable; 
class Factorial 
{ 
   static int f = 1; 
   static void fact(int n) 
   { 
     for(int i = n; i >= 1; i--) 
     { 
        f = f * i; 
     } 
   } 
}
public class FactorialTest { 
public static void main(String[] args) 
{ 
   Factorial.fact(4); 
   System.out.println(Factorial.f); 
 } 
}
Output: 
       24

Difference between Static Method and Instance Method in Java


There are mainly five differences between static method and instance method in Java. They are as follows:

1. A static method is also known as class method whereas, the instance method is also known as non-static method.

2. The only static variable can be accessed inside static method whereas, static and instance variables both can be accessed inside the instance method.

3. We do not need to create an object of the class for accessing static method whereas, in the case of an instance method, we need to create an object for access.

4. Class method cannot be overridden whereas, an instance method can be overridden.

5. Memory is allocated only once at the time of class loading whereas, in the case of the instance method, memory is allocated multiple times whenever the method is calling.


Recommended Tutorial for Interview

Can We override Static method in Java?


Key Points for Static (Class) Method:

  • Like static variables, static methods are bound with class, not with any specific object (instance) of a class.
  • You can access a static method using class name, without creating an object.
  • Static methods cannot access non-static (instance) members directly. To access instance variables or methods, you must create an object and use it explicitly.
  • Static methods do not have access to this or super. This is because they are not tied to any instance.
  • Methods declared with static keyword can be overloaded but not overridden.
  • From Java 8 onward, static methods (with public modifier implicitly) are allowed inside interfaces. This was not possible in earlier Java versions.