java – What does the :: operator mean?

Question:

I am learning JavaFX. Bumped into operator ::. Please explain what it means. Example:

public static LocalDate parse(String dateString) {
    try {
        return DATE_FORMATTER.parse(dateString, LocalDate::from);
    } catch (DateTimeParseException e) {
        return null;
    }
}

Answer:

This is a method reference , a new Java 8 language construct

For instance:

public static void main(String[] args) {
    List<String> list = Arrays.asList("str1", "str2", "str3");
    list.forEach(System.out::print);
}

The following will happen: the List interface inherits from Iterable, which has a forEach(Consumer<? super T> action) method.

Consumer is a functional interface, with one accept(T t) method that takes one parameter. In this case, consumer is the print method of the System.out class that takes a string.

A functional interface is an interface that has only 1 abstract method.

Scroll to Top