- Method References in Java
- 1. Overview
- 2. Reference to a Static Method
- 3. Reference to an Instance Method of a Particular Object
- 4. Reference to an Instance Method of an Arbitrary Object of a Particular Type
- 5. Reference to a Constructor
- 6. Additional Examples and Limitations
- 7. Conclusion
- How to Call by Reference in Java
- How to Call by Reference in Java?
- Conclusion
- About the author
- Farah Batool
Method References in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
One of the most welcome changes in Java 8 was the introduction of lambda expressions, as these allow us to forego anonymous classes, greatly reducing boilerplate code and improving readability.
Method references are a special type of lambda expressions. They’re often used to create simple lambda expressions by referencing existing methods.
There are four kinds of method references:
- Static methods
- Instance methods of particular objects
- Instance methods of an arbitrary object of a particular type
- Constructor
In this tutorial, we’ll explore method references in Java.
2. Reference to a Static Method
We’ll begin with a very simple example, capitalizing and printing a list of Strings:
List messages = Arrays.asList("hello", "baeldung", "readers!");
We can achieve this by leveraging a simple lambda expression calling the StringUtils.capitalize() method directly:
messages.forEach(word -> StringUtils.capitalize(word));
Or, we can use a method reference to simply refer to the capitalize static method:
messages.forEach(StringUtils::capitalize);
Notice that method references always utilize the :: operator.
3. Reference to an Instance Method of a Particular Object
To demonstrate this type of method reference, let’s consider two classes:
public class Bicycle < private String brand; private Integer frameSize; // standard constructor, getters and setters >public class BicycleComparator implements Comparator < @Override public int compare(Bicycle a, Bicycle b) < return a.getFrameSize().compareTo(b.getFrameSize()); >>
And, let’s create a BicycleComparator object to compare bicycle frame sizes:
BicycleComparator bikeFrameSizeComparator = new BicycleComparator();
We could use a lambda expression to sort bicycles by frame size, but we’d need to specify two bikes for comparison:
createBicyclesList().stream() .sorted((a, b) -> bikeFrameSizeComparator.compare(a, b));
Instead, we can use a method reference to have the compiler handle parameter passing for us:
createBicyclesList().stream() .sorted(bikeFrameSizeComparator::compare);
The method reference is much cleaner and more readable, as our intention is clearly shown by the code.
4. Reference to an Instance Method of an Arbitrary Object of a Particular Type
This type of method reference is similar to the previous example, but without having to create a custom object to perform the comparison.
Let’s create an Integer list that we want to sort:
List numbers = Arrays.asList(5, 3, 50, 24, 40, 2, 9, 18);
If we use a classic lambda expression, both parameters need to be explicitly passed, while using a method reference is much more straightforward:
numbers.stream() .sorted((a, b) -> a.compareTo(b)); numbers.stream() .sorted(Integer::compareTo);
Even though it’s still a one-liner, the method reference is much easier to read and understand.
5. Reference to a Constructor
We can reference a constructor in the same way that we referenced a static method in our first example. The only difference is that we’ll use the new keyword.
Let’s create a Bicycle array out of a String list with different brands:
List bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT");
First, we’ll add a new constructor to our Bicycle class:
public Bicycle(String brand)
Next, we’ll use our new constructor from a method reference and make a Bicycle array from the original String list:
bikeBrands.stream() .map(Bicycle::new) .toArray(Bicycle[]::new);
Notice how we called both Bicycle and Array constructors using a method reference, giving our code a much more concise and clear appearance.
6. Additional Examples and Limitations
As we’ve seen so far, method references are a great way to make our code and intentions very clear and readable. However, we can’t use them to replace all kinds of lambda expressions since they have some limitations.
Their main limitation is a result of what’s also their biggest strength: the output from the previous expression needs to match the input parameters of the referenced method signature.
Let’s see an example of this limitation:
createBicyclesList().forEach(b -> System.out.printf( "Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize()));
This simple case can’t be expressed with a method reference, because the printf method requires 3 parameters in our case, and using createBicyclesList().forEach() would only allow the method reference to infer one parameter (the Bicycle object).
Finally, let’s explore how to create a no-operation function that can be referenced from a lambda expression.
In this case, we’ll want to use a lambda expression without using its parameters.
First, let’s create the doNothingAtAll method:
private static void doNothingAtAll(Object. o)
As it is a varargs method, it will work in any lambda expression, no matter the referenced object or number of parameters inferred.
Now, let’s see it in action:
createBicyclesList() .forEach((o) -> MethodReferenceExamples.doNothingAtAll(o));
7. Conclusion
In this quick tutorial, we learned what method references are in Java and how to use them to replace lambda expressions, thereby improving readability and clarifying the programmer’s intent.
All code presented in this article is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
How to Call by Reference in Java
In Java, there are two types of function parameters: The Actual parameter and the Formal parameter. Actual parameters are passed during the function call in another function, whereas formal parameters are the parameters added at the function definition.
In functions, there are two ways to pass an argument or parameters: Call by value and Call by reference. The purpose of this article is to focus on how to call by reference in Java.
How to Call by Reference in Java?
When a function or a method is called in Java, call by reference is the term that refers to a parameter. This method’s core feature is that we use it to refer to the address of a variable. As a result, any change in the variable’s address will be reflected whenever the function that uses it is called or invoked.
Let’s try some examples with the help of the specified method.
In this example, first, we will create a method named “add()” by passing two integer type parameters, “x” and “y”. This method will output the sum of the given numbers. Also, the parameters of this method are called the formal parameters:
In the main() method, we call the add() method by passing the parameters that refer to the address of the formal parameters. Here, “a” and “b” are the reference parameters for variables “x” and “y”:
public static void main ( String [ ] args ) {
int a = 15 ;
int b = 83 ;
System.out.println ( «The sum of numbers a and b: » + add ( a,b ) ) ;
}
The given output indicates that the added parameters are successfully accessed and utilized:
In this example, we have two methods: “ref()” and “main()”. The ref() method will add the value of the specified parameters and then multiply it by “3”:
In the main() method, the third line calls the ref() method by passing arguments “a” and “b” that refers to the address of the formal parameters “x” and “y”:
We compiled all the instructions related to calling by reference in Java.
Conclusion
In Java, you can call the method by passing an argument as a reference in actual parameters. Invoking a method by using call by reference means the argument refers to the variable’s address. Whenever a function is called, the added changes will also reflect the variable. In this article, we have discussed the method for calling by reference in Java.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.