How to return 2 values from a Java method? How to return 2 values from a Java method? java java

How to return 2 values from a Java method?


Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.

Example (which doesn't use really meaningful names):

final class MyResult {    private final int first;    private final int second;    public MyResult(int first, int second) {        this.first = first;        this.second = second;    }    public int getFirst() {        return first;    }    public int getSecond() {        return second;    }}// ...public static MyResult something() {    int number1 = 1;    int number2 = 2;    return new MyResult(number1, number2);}public static void main(String[] args) {    MyResult result = something();    System.out.println(result.getFirst() + result.getSecond());}


Java does not support multi-value returns. Return an array of values.

// Function codepublic static int[] something(){    int number1 = 1;    int number2 = 2;    return new int[] {number1, number2};}// Main class codepublic static void main(String[] args) {  int result[] = something();  System.out.println(result[0] + result[1]);}


You could implement a generic Pair if you are sure that you just need to return two values:

public class Pair<U, V> { /**     * The first element of this <code>Pair</code>     */    private U first;    /**     * The second element of this <code>Pair</code>     */    private V second;    /**     * Constructs a new <code>Pair</code> with the given values.     *      * @param first  the first element     * @param second the second element     */    public Pair(U first, V second) {        this.first = first;        this.second = second;    }//getter for first and second

and then have the method return that Pair:

public Pair<Object, Object> getSomePair();