Describe a static method and demonstrate its use within a program

Static Method in Java:

In Java, a static method is a method that belongs to the class rather than to an instance of the class. It is associated with the class itself, not with the objects created from the class. Static methods are declared using the static keyword, and they can be called using the class name without creating an instance of the class.

Syntax:

public class ClassName {
    // Static method
    public static returnType methodName(parameters) {
        // Method body
    }
}

Example:

Let’s create a simple Java program that includes a static method. In this example, we’ll create a class called MathOperations with a static method for calculating the square of a number.

public class MathOperations {

    // Static method to calculate the square of a number
    public static int square(int num) {
        return num * num;
    }

    public static void main(String[] args) {
        // Calling the static method without creating an instance
        int result = MathOperations.square(5);

        // Displaying the result
        System.out.println("Square of 5: " + result);
    }
}

In this example:

  • The MathOperations class has a static method called square, which takes an integer parameter and returns the square of that number.
  • In the main method, we call the static method directly using the class name MathOperations.square(5).
  • The result is then displayed on the console.

Static methods are commonly used for utility functions, where the logic of the method does not depend on the state of an object and can be applied to the class as a whole. They are called using the class name and are not associated with any specific instance of the class.