How to return two values in Java?

To return two values in Java, create a Pair class and wrap those values in it.

Java does not support multiple return values, but you can emulate it with a simple Pair class.

// Pair.java
class Pair<FIRST, SECOND> {

  public FIRST first;
  public SECOND second;

  public Pair(FIRST first, SECOND second) {
    this.first = first;
    this.second = second;
  }
}

// SomeClass.java
void someMethodThatNeedsToReturnTwoValues() {
  // do stuff...
  String someValue = "first return value";
  int anotherValue = 123;
  // do stuff...

  return new Pair(someValue, anotherValue);
}

var returnValue = myMethodThatNeedsToReturnTwoValues();

System.out.println(returnValue.first); // first return value
System.out.println(returnValue.second); // 123