Table of Contents
Syntax
Glossary explanation
algorithm
Method 1: Method reference using double colon operator
Example
Output
Explanation
Method 2: Use instance variables to use the double colon operator for method references
Method 3: Use the double colon operator to refer to the instance method of any object.
Approach 4: Constructor referencing using double colon operator.
in conclusion
Home Java javaTutorial Double colon (::) operator in Java

Double colon (::) operator in Java

Aug 26, 2023 pm 01:29 PM
java programming double colon operator

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<Person> 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<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);
   }
}
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<employee> employeeSupplier = Employee::new;
      Employee employee = employeeSupplier.get();

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

      System.out.println(employee);
   }
}
</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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles