w3resource

Using Static Methods in Java: MathUtility Class Example

Java Static Members: Exercise-2 with Solution

Static Methods:
Write a Java program to create a class called "MathUtility" with a static method add that takes two integers and returns their sum. Demonstrate the usage of this static method in the main method without creating an instance of "MathUtility".

Sample Solution:

Java Code:

MathUtility.java

// Define the MathUtility class
public class MathUtility {
    // Static method add that takes two integers and returns their sum
    public static int add(int a, int b) {
        return a + b;
    }

    // Main method to demonstrate the usage of the static method
    public static void main(String[] args) {
        // Call the static method add without creating an instance of MathUtility
        int sum = MathUtility.add(10, 9);
        // Print the result
        System.out.println("The sum of 10 and 9 is: " + sum);
    }
}

Output:

The sum of 10 and 9 is: 19

Explanation:

  • Define the MathUtility class:
    • The MathUtility class is defined using the class keyword.
  • Static method add that takes two integers and returns their sum:
    • The static method add is defined to take two integer parameters (a and b) and return their sum.
  • Main method to demonstrate the usage of the static method:
    • The main method is defined to test the MathUtility class.
    • The static method add is called directly using the class name MathUtility without creating an instance of the class.
    • The result of the add method is stored in the variable sum.
    • The sum is printed to the console.

Note on Java Static Members:

In the above exercise, the static members work by:

  • Static Method: The static method add is defined in the "MathUtility" class. This method can be called directly using the class name without creating an instance of the class, which is demonstrated in the main method.
  • Main Method: The main method calls the add method using the class name "MathUtility" and prints the result. This shows how static methods can provide utility functions that are easily accessible without the need for object instantiation.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Static Members Previous: Using Static variables to Count Instances in Java.
Java Static Members Next: Using Static Blocks in Java: Initializer Class Example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/static_members/java-static-members-exercise-2.php