Double colon (::) operator in Java


In Java, the twofold colon (::) administrator, otherwise called the strategy reference administrator, is a strong element presented in Java 8. It gives a succinct and rich method for alluding to techniques or constructors without conjuring them. This administrator improves on the code and upgrades code coherence, making it an important instrument for designers. In this article, we will investigate the language structure of the twofold colon administrator, talk about its applications, and give code guides to better comprehension.

Syntax

The double colon operator consists of two colons (::) sandwiched between the class name or object reference and the method name. It serves as a shorthand notation for referring to a method or constructor in Java.

// A functional interface with a single abstract method
interface Printer {
   void print(String message);
}

// A class that implements the Printer interface
class ConsolePrinter {
   public static void printMessage(String message) {
      System.out.println(message);
   }
}

public class Main {
   public static void main(String[] args) {
      Printer printer = ConsolePrinter::printMessage;
      printer.print("Hello, World!");
   }
}

Explanation of Syntax

In the above code, we characterize a utilitarian connection point called Printer with a solitary dynamic technique print(). The ConsolePrinter class executes this connection point and gives an execution to the printMessage() technique. In the Principal class, we make an occasion of Printer utilizing the twofold colon administrator to allude to the printMessage() technique for the ConsolePrinter class. At long last, we conjure the print() strategy on the printer example, which thus calls the printMessage() technique.

Algorithm

  • To use the double colon operator in Java, follow these steps −

  • Define a functional interface with a single abstract method.

  • Implement the interface in a class and provide the method implementation.

  • Use the double colon operator to refer to the method or constructor.

  • Create an instance of the functional interface using the double colon operator.

  • Invoke the method on the instance, which will call the referenced method or constructor.

Approach 1: Method Reference using double colon operator

Approach 1 involves using the double colon operator to reference a static method of a class. This approach is useful when we want to pass a method reference that does not depend on any instance variables.

Example

// A functional interface with a single abstract method
interface Calculator {
   int calculate(int a, int b);
}

class MathUtils {
   public static int add(int a, int b) {
      return a + b;
   }
}

public class Main {
   public static void main(String[] args) {
      Calculator calculator = MathUtils::add;
      int result = calculator.calculate(5, 3);
      System.out.println("Result: " + result);
   }
}

Output

Result: 8

Explanation

Calculator is a functional interface with one abstract method calculate(). The static MathUtils function add() adds two numbers. The double colon operator creates a Calculator instance that references MathUtils' add() method. We call the calculator's compute() method with two numbers. Console outputs the result.

Approach 2: Method referencing using double colon operator using an instance variable

Approach 2 involves using the double colon operator to reference an instance method of a particular object.

Example

import java.util.ArrayList;
import java.util.List;

class Person {
   private String name;

   public Person(String name) {
      this.name = name;
   }

   public void printName() {
      System.out.println(name);
   }
}

public class Main {
   public static void main(String[] args) {
      List<Person> persons = new ArrayList<>();
      persons.add(new Person("Alice"));
      persons.add(new Person("Bob"));

      persons.forEach(Person::printName);
   }
}

Output

Alice
Bob

Explanation

In this example, we have an Individual class with a printName() strategy that prints the name of the individual. We make a rundown of Individual items and add two examples to it. Utilizing the twofold colon administrator, we reference the printName() strategy for the Individual class in the forEach() technique for the Rundown interface. This causes the printName() strategy to be conjured for every component in the rundown, printing their names to the control center.

Approach 3: Method referencing an instance method of any object using double colon operator.

Approach 3 involves referencing an instance method of any arbitrary object of a specific type using the double colon operator.

Example

import java.util.Arrays;
import java.util.List;

class StringUtil {
   public boolean isPalindrome(String s) {
      String reversed = new StringBuilder(s).reverse().toString();
      return s.equals(reversed);
   }
}

public class Main {
   public static void main(String[] args) {
      List<String> words = Arrays.asList("level", "hello", "radar", "world");

      StringUtil stringUtil = new StringUtil();
      long count = words.stream().filter(stringUtil::isPalindrome).count();

      System.out.println("Number of palindromic words: " + count);
   }
}

Output

Number of palindromic words: 2

Explanation

In this code scrap, a StringUtil class tests for palindromes with isPalindrome(). We create a list of words and use a stream to sort palindromic words using the isPalindrome() method recommended by the twofold colon administrator. Control center displays palindromic word count.

Approach 4: Constructor referencing using double colon operator.

Approach 4 involves using the double colon operator to reference a constructor.

Example

import java.util.function.Supplier;

class Employee {
   public String name;
   public int age;

   public Employee() {
      // Default constructor
   }

   public Employee(String name, int age) {
      this.name = name;
      this.age = age;
   }

   public String toString() {
      return "Employee [name=" + name + ", age=" + age + "]";
   }
}

public class Main {
   public static void main(String[] args) {
      Supplier employeeSupplier = Employee::new;
      Employee employee = employeeSupplier.get();

      employee.name = "John Doe";
      employee.age = 30;

      System.out.println(employee);
   }
}

Output

Employee [name=John Doe, age=30]

Explanation

In this model, we have a Representative class with a defined constructor. Utilizing the twofold colon administrator, we make a case of the Provider utilitarian point of interaction that references the Representative constructor. We then call the get() strategy on the employeeSupplier occurrence to get another Representative item. We set the name and age of the worker and print it to the control center utilizing the toString() technique.

Conclusion

The double colon (::) administrator in Java is a strong element presented in Java 8. It gives a brief and rich method for alluding to strategies or constructors without conjuring them straightforwardly. By utilizing the twofold colon administrator, we can work on our code, further develop comprehensibility, and influence the advantages of useful programming in Java. Understanding the grammar and different methodologies for utilizing the double colon administrator is fundamental for each Java designer. Along these lines, try to investigate and use this component in your future Java undertakings to improve your coding experience.

Updated on: 31-Jul-2023

954 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements