Monday, July 10, 2017

When to Make a Method Static in Java

Making a method static in Java is an important decision . Though, static keyword is one of the fundamental concepts, many times programmers gets confused to make a particular method static or not. In Java programming, main motivation for making a method static is convenience. You can call a static method without creating any object, just by using it's class name. So if you need a method, which you want to call directly by class name, make that method static. Utility classes e.g. java.lang.Math or StringUtils, are good examples of classes, which uses static methods. Before making a method static, you should look into limitation of static methods as well, as you can not override static method in Java

By keeping these properties in mind, we can make few rules, which will help to decide when to make a method static in Java and when to use them. 

In this Java article, we will learn more about benefits and limitation of making a method static, and also see couple of examples of static methods from JDK to learn when and how to use static method in Java.

What does static method do in Java

When you see a static method in Java code, What do you assume? What reasoning and assumptions a reader make, when he sees a static method? This is important to learn to  ensure we are using static method correctly.

1) Static method doesn't modify state of object. Since state of object is maintained as instance variables, and Java doesn't allow non static variables on static context. Modern days IDE like Netbeans also shows static method in italics to differentiate it from other methods.

2) Static method mostly operates on arguments, almost all static method accepts arguments, perform some calculation and return value.

How to use static method in Java

Rules to make a method static in Java

There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :

1) If a method doesn't modify state of object, or not using any instance variables.

2) You want to call method without creating instance of that class.

3) A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.

4) Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.

5) If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.

When to use static method in Java

How to use static method in JavaNow, we know the benefits and limitation of making a method static in Java, we can see couple of scenarios where we can use static methods. Factory design pattern provides a good use of static method. You can use static method to create instance of a class. Even Effective Java book advises about using static factory method, couple of example of these in Java library is creating thread pool from Executors class. Executors provides lots of static methods to create different types of thread pool e.g. public static ExecutorService newCachedThreadPool(), public static ExecutorService newFixedThreadPool(int nThreads) etc. Another interesting use of static methods from JDK is collection classes e.g. Collections and Arrays which provides lot of static utility methods to operate on different kinds of collection. Static method can also be combined with variable arguments to create a collection of explicitly elements e.g. EnumSet.of(E first, E... rest). Apart from these, if you loot at Apache commons lang library, you will find a pattern of utils class e.g. StringUtils, ArrayUtils, which provides utility methods to operate on String and arrays. One more interesting use of static method I have seen is valueOf() method inside different value classes e.g. java.lang.String, though this is also an example of factory method, but it's also a nice way to convert one type to another. For example valueOf() can also be used to convert String to Integer in Java. In short, it make sense to use static methods :

1) Along with creational design pattern e.g. Factory and Singleton.

2) As utility method, which operate on arguments.

3) A conversion tool e.g. valueOf().

That's all about when to make a method static in Java. We have seen benefits and limitation of making a method static, and few examples of static methods from JDK. JDK examples will also help you to decide when to use static method in Java.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!


Anonymous said...

nice explanation. thanks

how marker interface works internally. can you post regarding this topic.

Anonymous said...

Static is good to use. I prefer to make all method static and make object static, this way I can use method of any object from any other object without stupid use of references and new().

The new() operation should never have been put into the Java language. It is a terrible concept when you can simply declare everything static and make develop much easier.

Anonymous said...

can you provide some thoughts on making a method static or not with respect to multithreading?

Satyam said...

In addition to the answer to the above question who asked on making a method static or not with respect to multithreading?

If an method which is changing the state of an object and that object is used by multiple resources (resource could also be an object such as User,or any entity dependent on the changed object) then we can't make it static.Therefore an object operated in multi-threaded environment changing state of an object cannot be static.

Satyam said...

Hi Javin,please put some emphasize on second point as well in brief i.e when we need to call a method without using any instance such as Single threaded task i.e where only one object active at a time.

Great article

Anonymous said...

Thanks for this insightful article. This is the first time I know about use of static methods, in past I didn't even know about how to call a static method, but once I know that you can call them just by using class name, I am kind of making every method static in my code. This gives me so many error like you can not use non static members in static context, then I started making all my member variable static, now my program is working fine. Do you think its right? Does making all variable and method static has any disadvantage in Java?

Anonymous said...

One reason to make your method static must be performance. Static method Invocations is 15%-20% faster than virtual method invocation. It's also good programming practice, because you can tell from the method signature that calling the method can't alter the object's state.

Dhanashree said...

*Making all variables static has disadvantage.
Let's take an example of BankAccount class which has three variables accNo, accName, balance
for every account holder (instance of BankAccount) a copy of these three variable will be created if these are declared non static. However if we created them static then in this case only one copy would be created and every time a new instance is create the same copy would be shared and updated and there would be loss of data.
Identify the need of sharing data among instance only that variable should be static not all.
The good use of static key word is on final variables it assures a single copy of variable for all instances.
So don't make your all variables static instead create a one object in your static method to access the non static data.

Post a Comment