w3resource

Java Static Nested Class and Static Methods Example

Java Nested Classes: Exercise-6 with Solution

Static Nested Class and Static Methods:
Write a Java program to create an outer class called 'MathUtil' with a static nested class Calculator. The Calculator class should have a static method add(int a, int b) that returns the sum of a and b. Call the add() method from the main method.

Sample Solution:

Java Code:

MathUtil.java

// Outer class MathUtil
public class MathUtil {

    // Static nested class Calculator
    public static class Calculator {

        // Static method add that returns the sum of two integers
        public static int add(int a, int b) {
            return a + b;
        }
    }

    // Main method to demonstrate the usage of the static nested class and its method
    public static void main(String[] args) {
        // Calling the static method add of the static nested class Calculator
        int sum = MathUtil.Calculator.add(12, 14);
        
        // Printing the result
        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 26

Explanation:

  • Class MathUtil: The outer class containing the static nested class.
  • Static nested class Calculator: Contains a static method add(int a, int b).
  • Static method add(int a, int b): Takes two integers as parameters and returns their sum.
  • Main method: Demonstrates the usage of the static nested class and its static method by calling Calculator.add() and printing the result.

Note on Java Nested Classes:

Java nested classes can be static, meaning they don't need an instance of the outer class to be instantiated. In this exercise, the Calculator class is a static nested class within “MathUtil”. The add method in Calculator is also static, allowing it to be called directly using the class name without creating an instance. This demonstrates how static members can be used in different contexts to provide utility functions or shared data.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Static Members Previous: Java Inner Class Accessing Outer Class Members Example.
Java Static Members Next: Java Local Class Accessing Local Variables 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/nested-classes/java-nested-classes-exercise-6.php