Java 8 static methods examples

In Java 8, static methods were introduced in interfaces. Prior to Java 8, interfaces could only have abstract methods (methods without a body). However, Java 8 allowed interfaces to have static methods with a body, providing some form of implementation. This feature was introduced mainly to support the concept of “default methods” in interfaces, which allows you to add new methods to interfaces without breaking existing classes that implement those interfaces. In this post, we are going to see Java 8 static methods examples.

Static methods in interfaces are mainly used for the following purposes:

  1. Utility Methods: Static methods in interfaces can provide utility functions that are relevant to the interface’s concept. These methods can be called using the interface name without the need to create an instance of a class that implements the interface.
  2. Default Implementations: When you add a new method to an interface, classes that already implement that interface will not have that method implemented, which could lead to compilation errors. By providing a default implementation using static methods, you avoid this issue.

Here’s an example of static methods in interfaces with a main method:

interface MyInterface {
    // Abstract method (without a body)
    void regularMethod();

    // Static method with a body
    static void staticMethod() {
        System.out.println("This is a static method in the interface.");
    }
}

class MyClass implements MyInterface {
    @Override
    public void regularMethod() {
        System.out.println("Regular method implementation.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyInterface.staticMethod(); // Calling static method using interface name

        MyClass obj = new MyClass();
        obj.regularMethod(); // Calling regular method implementation
    }
}

In this example, the MyInterface interface defines a static method staticMethod() and an abstract method regularMethod(). The MyClass class implements the MyInterface interface and provides an implementation for the regularMethod().

When you run the Main class, the output will be:

This is a static method in the interface.
Regular method implementation.

Remember that static methods in interfaces are inherited but cannot be overridden by implementing classes. They are primarily intended to be called using the interface name.

Let’s see a few more examples.

  1. Example: Interface with Static Method
interface MyInterface {
    static void staticMethod() {
        System.out.println("This is a static method in MyInterface.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyInterface.staticMethod();
    }
}

Output:

This is a static method in MyInterface.

Explanation: In this example, the MyInterface interface contains a static method staticMethod(). The Main class calls this static method using the interface name. Static methods in interfaces can be called directly using the interface name and don’t require an instance of the implementing class.

  1. Example: Default Method with Static Method
interface MyInterface {
    default void defaultMethod() {
        System.out.println("Default method in MyInterface.");
    }

    static void staticMethod() {
        System.out.println("Static method in MyInterface.");
    }
}

public class Main implements MyInterface {
    public static void main(String[] args) {
        Main obj = new Main();
        obj.defaultMethod();
        MyInterface.staticMethod();
    }
}

Output:

Default method in MyInterface.
Static method in MyInterface.

Explanation: The MyInterface interface contains a default method defaultMethod() and a static method staticMethod(). The Main class implements the interface and calls both the default and static methods.

  1. Example: Interface Constants
interface Constants {
    double PI = 3.14159;
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Value of PI: " + Constants.PI);
    }
}

Output:

Value of PI: 3.14159

Explanation: In this example, the Constants interface defines a constant PI. Constants defined in interfaces are implicitly static and final. They can be accessed using the interface name.

  1. Example: Utility Method in Interface
interface StringUtils {
    static boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }
}

public class Main {
    public static void main(String[] args) {
        String text = "Hello, Java 8!";
        if (StringUtils.isNullOrEmpty(text)) {
            System.out.println("Text is null or empty.");
        } else {
            System.out.println("Text is not null or empty.");
        }
    }
}

Output:

Text is not null or empty.

Explanation: The StringUtils interface defines a utility method isNullOrEmpty() that checks if a given string is either null or empty. The Main class uses this utility method to determine if a string is null or empty.

  1. Example: Static Method in Comparator
import java.util.Comparator;

class MyComparator {
    static Comparator<String> getStringLengthComparator() {
        return Comparator.comparingInt(String::length);
    }
}

public class Main {
    public static void main(String[] args) {
        String[] words = {"apple", "banana", "grape", "orange"};
        Comparator<String> lengthComparator = MyComparator.getStringLengthComparator();
        Arrays.sort(words, lengthComparator);
        System.out.println("Sorted words: " + Arrays.toString(words));
    }
}

Output:

Sorted words: [grape, apple, banana, orange]

Explanation: The MyComparator class contains a static method getStringLengthComparator() that returns a comparator for sorting strings by their lengths. The Main class uses this static method to create a comparator and sort an array of words based on their lengths.

Objective questions – Test yourself.

Question 1:
Which of the following statements about static methods in Java 8 interfaces is correct?

A) Static methods in interfaces must be implemented by all classes that implement the interface.
B) Static methods in interfaces cannot have a body.
C) Static methods in interfaces are called using an instance of the implementing class.
D) Static methods in interfaces are inherited but cannot be overridden.

Question 2:
What is the primary purpose of adding static methods to Java interfaces in Java 8?

A) To enforce the implementation of static methods in all implementing classes.
B) To enable multiple inheritance in Java.
C) To provide a way to create instance methods in interfaces.
D) To add utility methods and provide default implementations without breaking existing classes.

Question 3:
In a Java interface named Constants, if a variable is declared as static final int VALUE = 42;, what does it imply?

A) The variable cannot be accessed outside the interface.
B) The variable can be modified after initialization.
C) The variable’s value can be different for each class implementing the interface.
D) The variable represents a constant value that cannot be changed.

Question 4:
Which of the following best describes the concept of a “default method” in Java 8 interfaces?

A) A method that is automatically called when an object is created.
B) A method that has a default implementation in the interface itself, but can be overridden by implementing classes.
C) A method that is always called before other methods in the interface.
D) A method that is required to be implemented by all classes that use the interface.

Question 5:
In a Java interface named StringUtils, if a static method is defined as static boolean isNullOrEmpty(String str), what is the purpose of this method?

A) To check if a string is null or empty.
B) To convert a string to uppercase.
C) To concatenate two strings.
D) To remove whitespace from a string.


Answers:

  1. D) Static methods in interfaces are inherited but cannot be overridden.
  2. D) To add utility methods and provide default implementations without breaking existing classes.
  3. D) The variable represents a constant value that cannot be changed.
  4. B) A method that has a default implementation in the interface itself, but can be overridden by implementing classes.
  5. A) To check if a string is null or empty.

That’s all about Java 8 static methods examples.

Other Java 8 examples.