Creating and Using Static Methods in Java

Introduction

In previous lessons, you have created a basic Java program. You’ve seen how the main method executes and learned about static blocks. In this blog post, we will delve into creating and using static methods. This will help you keep your code organized and efficient.

Setting Up a New Class

First, we’ll use a different class to keep our code organized. Right-click on the default package, create a new class, and name it StaticDemo. Select the option that includes the public static void main method and finish creating the class. Once done, maximize the editor window, place your cursor inside the main method, and clean up the code if necessary.

Creating a Static Method

We start by creating a static method using the static keyword. Since we don’t want this method to return anything, we will use the void keyword. Here’s an example:

public static void methodOne() { System.out.println(“Inside methodOne”);}

In the example above, the displayMessage method is created as a static method. This means it can be called without creating an instance of the class.

Calling a Static Method

To call a static method, you simply use the class name followed by a dot and the method name. Here’s how you do it in the main method:

public class StaticDemo {
public static void main(String[] args) { System.out.println(“Inside main”); StaticDemo.methodOne();
}
public static void methodOne() { System.out.println(“Inside methodOne”);
}}

As shown above, the displayMessage method is called directly within the main method. The output will be: Hello, this is a static method!

Benefits of Static Methods

Static methods have several advantages:

  • Memory Efficiency: Static methods are loaded into memory once, reducing the overhead of creating multiple instances.

  • Utility Functions: They are perfect for utility functions that don’t rely on instance variables.

  • Global Access: Static methods can be accessed globally within the application.

Conclusion

In this blog post, we explored how to create and use static methods in Java. We set up a new class, created a static method, and called it within the main method. Static methods offer various benefits such as memory efficiency and global access, making them a valuable tool in Java programming.

One thought on “Creating and Using Static Methods in Java

Leave a Reply

Your email address will not be published. Required fields are marked *