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!"); } }
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); } }
Output
Result: 8
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); } }
Output
Alice Bob
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); } }
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.
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>
Output
Employee [name=John Doe, age=30]
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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 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 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 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.

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

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

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.
