-4

I'm just a beginner in Java. When should I use double colon?

import java.util.stream.*;

class GFG {

    public static void main(String[] args)
    {
        // Get the stream
        Stream<String> stream= Stream.of("Geeks", "For", "Geeks", "A", "Computer", "Portal");

        // Print the stream
        // using double colon operator
        stream.forEach(System.out::println);
    }
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Aymaan
  • 11
  • 1
  • 5
    Does this answer your question? [:: (double colon) operator in Java 8](https://stackoverflow.com/questions/20001427/double-colon-operator-in-java-8) – Turamarth Oct 02 '20 at 13:58
  • As for when to use it, you can pretty much use it any time you have a specific method you want passed in as a [functional interface](https://www.geeksforgeeks.org/functional-interfaces-java/) parameter. If you're unfamiliar with what this does, it allows a method to be used as a parameter in other methods so that the initial method can have it's functionality defined in a more abstract fashion (just like in the `foreach` where you don't have to specify what will be done for each element in the `foeach` call, that's handled by the given method). – Tim Hunter Oct 02 '20 at 14:14

1 Answers1

1

The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate to the method.

GfG

Spectric
  • 27,594
  • 6
  • 14
  • 39