Static Method in Java

Filed Under: Java

Static Method in Java belongs to the class and not its instances. A static method can access only static variables of class and invoke only static methods of the class.

Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. For example Collections class.

Java Wrapper classes and utility classes contain a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

Static Method Example

Let’s look at a few simple static method examples.


public class MathUtils {

public static long add(long i, long j) {
    return i + j;
}

//static util method
public static int addInts(int i, int...js){
    int sum = i;
    for(int x : js) sum+=x;
    return sum;
}

}

Calling a Static Method in Java

We can call a static method using ClassName.method. For example;


MathUtils.add(100L, 20L);
MathUtils.addInts(1, 2, 3, 4);

When to create static methods in java

  • Static Method doesn’t require instance creation, so it’s generally faster and provides better performance. That’s why utility class methods in Wrapper classes, System class, Collections class are all static methods.
  • It’s possible to write fluent code when static imports are used. You will see this a lot in testing frameworks such as JUnit and TestNG.
  • When your method only depends on its parameters, object state has no effect on the method behavior. Then you can create the method as static.

In all other cases, you should be better with the non-static method.

Java Interface Static Method

From Java 8 onwards, we can define static methods in interfaces too. Java interface static method can’t be overridden in the implementation classes. This feature helps us in avoiding undesired results in case of poor implementation in implementation classes. Let’s look into this with a simple example.


public interface MyData {

static boolean isNull(String str) {
		System.out.println("Interface Null Check");

		return str == null ? true : "".equals(str) ? true : false;
	}
}

That’s all for a quick introduction of the static method in java.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages