ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

What is a Static Method in Java?

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Static Method in Java

Making your method static means that you do not need to instantiate an object in order to access that method of a certain class. It can be directly accessible to the main program by simply calling the class name and the class method.

How to have static method in Java?

To make a static method, just add a ‘static’ word before the data type of the method name. For example:

public static int methodname();

How to call the Static Method in the main Program?

You can call the static method in the main program like this:

className.methodName();

It also works if you declare an object for the class to access the method but that is discourage, because in the first place static is considered as a short cut on accessing the method of the class even without the object declaration (though in my other examples here with a static method, I still declared an object for the methods, it’s your turn to make the practice correct, I shall mind this practice in my future codes).


Like always, you can see how to use it, and how it behaves by providing a complete running program for it. For the sample java program on Static method, see the source code and the program algorithm below.

Program Algorithm:

The program is just simple, we will just show how this static method works. So, we will just output a string inside a method. If you have a program in mind, try using static method and access it directly in your main program.

Java Source Code for Static Method

//main class



package static_method_in_java;


public class Main {

  
    public static void main(String[] args) {

        Static_Method.sample_static_method();
    }

}

//java class

package static_method_in_java;

public class Static_Method {
    public static void sample_static_method()
    {
        System.out.println("This is how Static Method works. Simple isn't it? :)");
        System.out.println("Aisha91 at your Service. Bow! LoL, just kidding.");
    }

}

Sample Output:

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article