Use of double colon operator in Java

Hey Everyone! In this article today, we will learn about the use of a double colon operator in Java.

Double Colon Operator in Java

Usually, lambda expressions are used to create anonymous methods in Java to get a particular output. Double colon operator is also known as a method referencing operator. Double Colon operator(::) work exactly like lambda expressions. This operator directly references the name of the method to be called. The method that is referenced by the double colon operator is invoked whenever a call is made to the method.

Double Colon Operator Java Program -1

import java.util.List;
import java.util.*;

 //interface fact created
interface fact {
    //method declared as it is an interface i.e no definition provided
    Shop getItems(List items);

class Shop 
    //List created 
     List groceries;
    public Shop(List passed_groceries) //passed_groceries is a list that acquires value from main method.
        groceries = passed_groceries;
  System.out.println("Grocery items added");

public class Program 
   public static void main(String[] args) throws Exception
                System.out.println("Demonstrating the use of double colon operator in Java. ");
                // :: double colon operator used to refer the method.
                fact met_ref = Shop::new;		//also known as method referencing operator.
    Shop obj1 = met_ref.getItems(new ArrayList());




Demonstrating the use of double colon operator in Java. 
Grocery items added
BUILD SUCCESSFUL (total time: 0 seconds)

In the above program,  the constructor of the class Shop is referred to through the double colon operator in the main method (method referencing operator).

Leave a Reply

Your email address will not be published. Required fields are marked *