- Java

Difference between static and non-static methods in java

In this article let’s learn how static and non-static methods are used in a program.Usually when we want to access class members we create the object of the class and then access through the object as reference.There is another way to do this without creating the object(accessing directly by class name)  i.e by using the keyword static before the class members.We can declare both methods and variables as static. Static methods can directly call other static methods and can directly access static data.For non-static methods allocation of memory is multiple times but memory allocation for static is only once.  And there are also static blocks which are executed when the class is loaded(we’ll see about this in further articles).So now don’t confuse between static blocks and static methods because they are completely different.

Let’s see the difference between static and non-static methods:

Static method declared in class:

import java.util.*;
class staticmethod
{
    public static void main(String args[])
    {
       int a,b,c;
       a=10;
       b=20;
       c=sum(a,b);//accessing the static methods
       System.out.println("Sum="+c);
    }
    static int sum(int x,int y)
    {
       int z;
       z=x+y;
       return(z);
    }
}




Non-static method declared in class

import java.util.*;
class nonstatic
{
    public static void main(String args[])
    {
        int a,b,c;
        a=10;
        b=20;
        nonstatic obj= new nonstatic(); //creating instance of same class in order to access non-static function
        c=obj.sum(a,b); //accessing non-static methods
        System.out.println("Sum="+c);
    }
    int sum(int x,int y)
    {
        int z;
        z=x+y;
        return(z);
    }
}

Conclusion: From the above two programs we can see that static methods are easier to access when compared non-static methods of class.Because we can directly call the function in case of static but that doesn’t happen in non-static.

Leave a Reply