Scope Resolution Operator in Java
C++ supports the scope resolution operator (::) that allows us to resolve the ambiguous call or reference to identifiers. Like C++, Java does not support the scope resolution operator. Java uses the same operator (::) but with different names. The scope resolution operator in Java is known as the method reference operator or double colon operator. In this section, we will discuss the scope resolution operator in Java.
The method reference operator is used to call a method by referring to it with the help of its class directly. We can use the method reference operator instead of lambda expressions because it behaves the same as lambda expressions.
The only difference between lambda expression and method reference operator is that instead of providing a delegate to the method it uses a direct reference to the method by name. The target reference is placed before the operator (::) and the method name is written after it.
Syntax:
Both lambda expression and the method reference operator are the ways to call the existing method with method reference that provides better readability. Let’s understand it through an example.
First, we will create a Java program and use the lambda expression to access a list. It also clears the differences between lambda expression and the method reference operator.
LambdaExpressionExample.java
Output:
San Jose Las Vegas Austin New York Denver Portland
In the above program, we have used the lambda expression to access the elements.
Let’s use the method reference operator in the above program to access the elements. We have made a slight change in the above program.
MethodReferenceOperatorExample.java
Output:
San Jose Las Vegas Austin New York Denver Portland
Using lambda expression and method reference operator, we get the same output. Therefore, it is clear that these are the ways to call the existing method with method reference.
Types of Method References
There are four types of method references in Java:
Types | Description | Syntax | Example |
---|---|---|---|
Reference to a static method | It is used to refer a static method from a class. | ContainingClass::staticMethodName | Math::floor is equivalent to Math.floor(x) |
Reference to an instance method of a particular object | It refers to an instance method using a reference to a supplied object. | containingObject::instanceMethodName | System.out::println is equivalent to System.out.println(x) |
Reference to an instance method of an arbitrary object of a particular type | It invokes the instance method on a reference to an object supplied by the context. | ContainingType::methodName | String::indexOf is equivalent to str.indexOf() |
Reference to a constructor | It gives reference to a constructor. | ClassName::new | LinkedList::new is equivalent to new LinkedList() |