9 difference between static vs non-static method in Java - Answer

One of the key differences between a static and a non-static method is that the static method belongs to a class while the non-static method belongs to the instance. This means you can call a static method without creating an instance of the class by just using the name of the class like the  Math.random() for creating random numbers in Java. Often utility methods that don't use the member variables of the class are declared static. On the other hand, you need an instance of the class to call a non-static method in Java. You cannot call it without creating an object because they are dependent upon the member variables which have different values for different instances.  

One more important difference between the static and non-static method is that you cannot use a non-static member variable inside a static method, you cannot even call a non-static method from the static method, but the opposite is true e.g. you can call a static function from a non-static method in Java.

The static is one of the concepts, which always creates some doubt on Java programmers mind, especially beginners, hence it's very important for them to read a book which explains these fundamentals in detail. The Core Java Volume 1 - Fundamentals by Cay S. Horstmann is one such book and if you haven't read it yet, you should check it. One of the better books to learn Java fundamentals.




Difference between Static and Non-Static Method in Java

Now, let's see some more differences between a static and non-static method in Java. There are a lot of implications of making a method static in Java, like you cannot override static methods, which we will see in this part of the article.

1. Static method cannot be overridden
Yes, this is another key difference between a static and non-static method. You can override a non-static or instance method but the static method cannot override in Java. Though, when you declare the same static method in the subclass, it hides the method from the superclass, also known as method hiding in Java. See this article to learn more about overriding and static in Java.


2. You cannot use this and supper inside the static method
Both this and super are associated with an instance and because you cannot use a non-static context inside a static method in Java, you cannot use both this and super inside the static method as well.




3. You cannot use non-static variables like instance variables inside a static method
Apart from this and super, you cannot use any non-static or instance member variable inside a static method in Java. It will result in a compile-time error as shown in the following code:

difference between static and non-static method in Java


4. You can call static methods on null references
This is one of the hidden detail of the Java programming language that you can call a static method on null reference and code will not throw NullPointerException. This happens because a static method is bonded at compile time by using the class name only.

/**
 * Java Program to demonstrate difference between static
 * vs non-static methods
 * 
 * @author WINDOWS 8
 *
 */
public class TestString {

    public static void main(String[] args) {
        
        TestString t = null;
        t.display(); // no null pointer exception       
    }
     
    public static void display(){
        System.out.println("Inside static method");
    }
    
    public void show(){
        System.out.println("Inside non-static method");
    }
    
}

Output
Inside static method

5. A static method is bonded during compile time.
This is true and that's why you can call a static method without creating any instance. Due to this property, you can also overload a static method in Java but you cannot override it, which potentially requires runtime binding.


6. When to use static and instance method in Java
Both utility and factory methods are good candidates for making static because they don't have any side-effect and don't require any data outside of method arguments. On the other hand, the instance method usually makes changes to the object's state by modifying member variables' values.


7. The static method usually operates on function arguments passed to them.
The functions in java.lang.Math is a good example as they only need input arguments.  Java's built-in methods Arrays.sort() and Collections.sort() are good examples of static methods. On the other hand put() and get() methods of HashMap are good examples of instance or non-static methods.


8) Static methods belong to the class.
Static methods belong to the class, so can be called without a specific instance of that class needed. For example, the Math class contains many static methods which means you can use these methods without needing to instantiate the Math class. Also, the main method is usually static because it is called first before there is any time to instantiate a class!

Non-static methods can only be called on an instance of the class itself, and they usually do something that depends on the individual character of the class (e.g. play with variables).


9. You cannot call a non-static method from the static method in Java
Yes, this is true, trying to do so will result in a compile-time error but the opposite is true i.e. you can call a static method from a non-static method without any issue as shown in the following code example:

cannot call a non-static method from static in Java



That's all about the difference between the static and non-static methods in Java. It's one of the fundamental concepts in Java and every Java Programmer should know the rules of static methods and understand when to make a method static in Java. The general guideline is to use a static method for utilities, conversion, and factory methods. You can also make a method static if it doesn't have any side-effect on an object.

6 comments:

  1. Great article, very informative. A little error needs being corrected "2) You cannot use this and supper" to super.

    ReplyDelete
  2. The key difference is that a static method will always operate in the same way regardless of context, while a non-static method may operate differently between implementations. The output of a static method is only affected by the arguments you give it, while the output of a non-static method can also be affected by the state of the object that defines it.
    Let's take Math.pow(int number, int power) as an example. This is a static method, meaning that we don't need to create a Math object in order to call it. This is because its output is affected solely by the values of number and power. We could create a billion different Math objects, but pow() would always work the same for each of them.
    Now let's say I want to write a new Math class that allows for alternate realities, where math works differently. I can no longer make pow() a static method, because the output may be different between these realities even though the arguments are identical. I have to take the context of the method into account (i.e. what reality it was called in). To do this, I can create separate Math objects and specify certain parameters specific to their respective realities. Then, when I call pow() on one of these objects, it will calculate the output appropriate for that reality. Because I have to create a Math object to get the correct implementation of pow(), the method is no longer static.

    ReplyDelete
  3. The biggest disadvantage of making a static method is loss of Pollymorphism. You are limiting object oriented capability of your code by making a method static, simply because you cannot override them.

    ReplyDelete
    Replies
    1. @Anonymous, very insightful comments. great point of view.

      Delete
  4. Hii.. This blog is superb. Lot of information. But there is a typo here. It should be like "On the other hand, you need an instance of the class to call a static method in Java." instead of "On the other hand, you need an instance of the class to call a non-static method in Java."

    ReplyDelete
    Replies
    1. @amara, thanks for pointing out, I'll correct that.

      Delete

Feel free to comment, ask questions if you have any doubt.