“static” keyword in a method in a top-level class that represents a utility for mathematical operations?

212    Asked by CarolynBuckland in Salesforce , Asked on Mar 19, 2024

 There is a scenario where I am developing a Java-based application where I have a top-level class that represents a utility for mathematics operations. Discuss with me how can I use the “static” keyword in methods within this particular class for the purpose of creating reusable and efficient functionality for performing common mathematical calculations across your application. 

Answered by debbie Jha

In the context of Salesforce, here is how you can use the “static” keyword for the mathematical operations in a top-level utility class:-

Create a utility class

Firstly, you would need to create a top-level utility class for the purpose of containing your mathematical operations. This class should have a private constructor for preventing instantiation since it is meant to be used statically.

Declare static methods

Within the utility class, you can declare your mathematical operations as “static” methods. This would allow you to call these methods without creating an instance of the utility class.

Example coding:-

Public class MathUtility {
    // Private constructor to prevent instantiation
    Private MathUtility() {
        // Empty private constructor
    }
    // Static method for addition
    Public static int add(int a, int b) {
        Return a + b;
    }
    // Static method for subtraction
    Public static int subtract(int a, int b) {
        Return a – b;
    }
    // Static method for multiplication
    Public static int multiply(int a, int b) {
        Return a * b;
    }
    // Static method for division
    Public static double divide(int a, int b) {
        If (b != 0) {
            Return (double) a / b;
        } else {
            Throw new IllegalArgumentException(“Cannot divide by zero.”);
        }
    }
    Public static void main(String[] args) {
        // Example usage of static methods
        System.out.println(“Addition: “ + MathUtility.add(5, 3));
        System.out.println(“Subtraction: “ + MathUtility.subtract(10, 4));
        System.out.println(“Multiplication: “ + MathUtility.multiply(6, 7));
        System.out.println(“Division: “ + MathUtility.divide(20, 4));
    }
}


Your Answer

Interviews

Parent Categories