Java Coding Style – How to Return Multiple Values

coding-stylejava

Sometimes you want to return multiple values from a function. How is this normally done in Java?

One option is to use an array, like this Python snippet that returns a list or tuple:

value, success = read_unreliably()
if success:
    print value

Another option would be to return a hash/dict, like this JavaScript example:

var result = readUnreliably()
if (result.success) {
    alert(value);
}

One more would be to create a custom object just for this purpose, like this Java example:

ReadUnreliablyResult result = readUnreliably()
if (result.getSuccess()) {
    System.out.println(result.getValue());
}

Of course you can also just use some global variables to store what you need instead of passing things around, but let's just say that's not an option.

Best Answer

How is this normally done in Java?

Painfully.

One option is to use an array, like this Python snippet that returns a list or tuple...

Another option would be to return a hash/dict, like this JavaScript example...

These techniques don't work well in Java; the values would have to be downcast from Object.

One more would be to create a custom object just for this purpose, like this Java example...

This is most common, but it is tedious to create all those little classes. In C++ it is common to use std::pair but this is not commonly done in Java.

With Lombok it is quite easy to create little custom objects:

@RequiredArgsConstructor
public class X {
  private final boolean status;
  private final byte[] data;

}