W3docs

How to return 2 values from a Java method?

There are a few ways you can return multiple values from a Java method:

There are a few ways you can return multiple values from a Java method:

  1. Return an array: You can create an array that contains the values you want to return, and then return the array. For example:

public static int[] getValues() {
  return new int[] {1, 2};
}

// usage:
int[] values = getValues();
  1. Return a custom object: You can create a custom object that contains the values you want to return, and then return an instance of that object. For example:

public class Values {
  private int value1;
  private int value2;

  public Values(int value1, int value2) {
    this.value1 = value1;
    this.value2 = value2;
  }

  // getters and setters
}

public static Values getValues() {
  return new Values(1, 2);
}

// usage:
Values values = getValues();
  1. Use a standard library pair: The Java standard library provides AbstractMap.SimpleEntry to return a pair of values without external dependencies. For example:

import java.util.AbstractMap;

public static AbstractMap.SimpleEntry<Integer, Integer> getValues() {
  return new AbstractMap.SimpleEntry<>(1, 2);
}

// usage:
AbstractMap.SimpleEntry<Integer, Integer> values = getValues();
int value1 = values.getKey();
int value2 = values.getValue();
  1. Use a Java 16+ record: Starting with Java 16, you can use a record to return multiple values concisely without boilerplate. For example:

public record Values(int value1, int value2) {}

public static Values getValues() {
  return new Values(1, 2);
}

// usage:
Values values = getValues();
int value1 = values.value1();
int value2 = values.value2();