Skip to content

How to return multiple values?

There are a few different ways to return multiple values from a method in Java:

  1. Use an array: You can create an array of the values you want to return, and return the array. The calling method can then access the individual elements of the array to get the return values.

    java
    public int[] getValues() {
        return new int[]{1, 2};
    }
  2. Use a Java object: You can create a Java class that contains the values you want to return as instance variables. The calling method can then access these instance variables to get the return values.

    java
    public class Result {
        public int a;
        public String b;
    }
    public Result getValues() {
        return new Result();
    }
  3. Use a Java 14+ record: Records provide a concise, standard way to group multiple values together. They automatically generate constructors, getters, and equals/hashCode methods.

    java
    public record Result(int a, String b) {}
    public Result getValues() {
        return new Result(1, "hello");
    }
  4. Use a Java tuple: There are a few libraries available that provide tuple classes for Java, which allow you to group multiple values together and return them as a single object. The calling method can then access the individual elements of the tuple to get the return values.

    java
    // Using Apache Commons Lang3
    public Pair<Integer, String> getValues() {
        return new Pair<>(1, "hello");
    }

It's worth noting that returning multiple values in this way can make your code more difficult to read and understand, and it is generally better to use a more structured approach such as using an object or a tuple if you need to return multiple values.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.