Java
methods
return values
programming tips
coding techniques

How to return 2 values from a Java method?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Returning multiple values from a method in Java is a common requirement but can be somewhat unintuitive since Java does not support multi-valued returns natively like some other languages such as Python or JavaScript. However, multiple approaches can be used to achieve this. This article explores various techniques to return two values from a Java method along with their technical explanations and examples.

Using an Array or Collection

Arrays

The simplest way to return multiple values is by using an array. This approach involves storing the values within an array and returning it. This method works perfectly for values of the same type.

Example

java
1public String[] getNames() {
2    String[] names = new String[2];
3    names[0] = "John";
4    names[1] = "Doe";
5    return names;
6}

Lists

You can also make use of Java Collections, such as a List, to return multiple values. This can be especially useful if the number of return values isn't fixed.

Example

java
1import java.util.Arrays;
2import java.util.List;
3
4public List<String> getNamesList() {
5    return Arrays.asList("John", "Doe");
6}

Using a Custom Class

Creating a custom class is one of the most recommended ways when you have multiple values of different types or when the values logically belong together.

Example

java
1public class NamePair {
2    private String firstName;
3    private String lastName;
4
5    public NamePair(String firstName, String lastName) {
6        this.firstName = firstName;
7        this.lastName = lastName;
8    }
9
10    public String getFirstName() {
11        return firstName;
12    }
13
14    public String getLastName() {
15        return lastName;
16    }
17}
18
19// Method to return the custom class instance
20public NamePair getNames() {
21    return new NamePair("John", "Doe");
22}

Using Pair or Tuple Libraries

Java doesn't have a built-in Pair class, but external libraries such as Apache Commons Lang or JavaFX provide these utilities. Optionally, you could use tuples if you're working with libraries like Vavr or Javatuples.

Example Using Apache Commons Lang3

xml
1// Maven dependency
2<dependency>
3    <groupId>org.apache.commons</groupId>
4    <artifactId>commons-lang3</artifactId>
5    <version>3.12.0</version>
6</dependency>
java
1import org.apache.commons.lang3.tuple.Pair;
2
3// Method to return a Pair
4public Pair<String, String> getNamePair() {
5    return Pair.of("John", "Doe");
6}

Using Map Interface

The Map interface is a suitable choice when you have pairs of values with clear key-value relationships.

Example

java
1import java.util.HashMap;
2import java.util.Map;
3
4public Map<String, String> getNamesMap() {
5    Map<String, String> nameMap = new HashMap<>();
6    nameMap.put("firstName", "John");
7    nameMap.put("lastName", "Doe");
8    return nameMap;
9}

Summary Table

Method ApproachUse CaseExample Code ComplexityWhen to Use
ArraySame-type valuesSimpleWhen values have the same data type
ListSame-type, flexible sizeAverageWhen multiple values of the same type and quantity vary
Custom ClassDifferently-typed values, logical groupingComplexWhen values logically belong to a single entity
Pair/Tuple LibrariesTwo values, clear relationshipMedium to ComplexSimplifies code with two associated values
Map InterfaceKey-value pairs relationshipMediumWhen pairs need a key-value logic

Additional Details

Handling Nulls and Optional Values

When dealing with optional or nullable values, Java's Optional class can be considered. This adds more readability and safety around handling null cases.

Performance Considerations

Using custom objects can introduce object overhead, so when performance is a critical aspect, choosing arrays might be beneficial for primitive types. For complex objects, the performance difference is generally negligible.

Future Language Enhancements

While Java doesn't yet natively support multiple return values, future enhancements, including possible language features in new Java versions, might address this limitation. Always keep an eye on the incorporation of Record classes introduced in Java 14 as they could also provide a structured yet compact way to return multiple values.

Java offers multiple ways to return two or more values from a method, each with specific contexts where it's most applicable. Understanding these different approaches helps in choosing the best solution for your problem, balancing code readability, performance, and functionality.


Course illustration
Course illustration

All Rights Reserved.