Static Method
A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static method is the main() method.
Let's see an example of the static method.
public class Main
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("I am inside the static method !");
}
}
Output :
I am inside the static method !
Non Static Method or Instance Method
It is a non-static method defined in the class. Before calling or invoking the instance method, it is necessary to create an object of its class.
As to invoke this method we need to create an oobject i.e. instance of the class, so it is also called as instance method.
Let's see an example of an instance method.
public class InstanceMethodExample
{
int s;
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(5, 8);
}
//instance method
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output :