Home > Java > Java Tutorial > body text

Double colon (::) operator in Java

PHPz
Release: 2023-08-26 13:29:17
forward
871 people have browsed it

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 is used as a shorthand notation for referencing methods or constructors 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!");
   }
}
Copy after login

Glossary explanation

In the above code, we use a utility connection point called Printer to define a class with a single dynamic method print(). The ConsolePrinter class implements this connection point and provides an implementation for the printMessage() method. In the Principal class, we create a Printer instance using the double colon operator to reference the printMessage() method of the ConsolePrinter class. Finally, we call the print() method of the printer instance, which in turn calls the printMessage() method.

algorithm

  • To use 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 implementation of the method.

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

  • Use the double colon operator to create an instance of a functional interface.

  • Calling this method on an instance will call the referenced method or constructor.

Method 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);
   }
}
Copy after login

Output

Result: 8
Copy after login

Explanation

Calculator is a functional interface with an abstract method calculate(). The static MathUtils function add() is used to add two numbers. The double colon operator creates a Calculator instance that references the MathUtils add() method. We call the calculator's compute() method with two numbers. Console output results.

Method 2: Use instance variables to use the double colon operator for method references

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 persons = new ArrayList<>();
      persons.add(new Person("Alice"));
      persons.add(new Person("Bob"));

      persons.forEach(Person::printName);
   }
}
Copy after login

Output

Alice
Bob
Copy after login

Explanation

In this example, we have an Individual class, which has a printName() strategy for printing the name of the individual. We created a list of Individual projects and added two examples. Using the double colon operator, we reference the printName() strategy of the Individual class in the forEach() method of the List interface. This causes the printName() method to be called, printing the name of each element in the list to the console.

Method 3: Use the double colon operator to refer to the instance method of any object.

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 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);
   }
}
Copy after login

Output

Number of palindromic words: 2
Copy after login

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.

Method 4 involves referencing the constructor using the double colon operator.

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);
   }
}
Copy after login

Output

Employee [name=John Doe, age=30]
Copy after login

Explanation

In this model, we have a Representative class with a defined constructor. Using the double colon operator, we create an instance of the Provider function interaction point that references the Representative constructor. Then, we call the get() method on the employeeSupplier instance to obtain another Representative object. We set the employee's name and age and print it to the console using the toString() method.

in conclusion

The double colon (::) operator in Java is a powerful element introduced in Java 8. It provides a concise and rich way to reference methods or constructors without calling them directly. By using the double colon operator, we can improve the code, increase readability, and take advantage of the benefits of functional programming in Java. Understanding the syntax and different ways of using the double colon operator is necessary for every Java developer. Therefore, be sure to explore and use this feature in your future Java projects to enhance your coding experience.

The above is the detailed content of Double colon (::) operator in Java. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!