There is no such thing as an out
parameter in Java, so you have to imitate passing output parameters with pass-by-value by adding an extra level of indirection.
A very simple approach is passing a StringBuilder
- a mutable object which could be modified by the caller:
public static Result getFromLocation(StringBuilder additionalInformation) {
...
// Method modifies the mutable object
additionalInformation.append("Some additional text");
...
}
The caller would have to provide a non-null StringBuilder
, like this:
StringBuilder info = new StringBuilder();
Result res = getFromLocation(info);
// Caller sees information inserted by the method
System.out.println(info);
In situations when you receive back an error message, a better approach is to throw a checked exception. This way you would be able to provide the error message out of bounds, and cleanly separate error processing from the code for the main functionality of your system:
class AddressRetrievalExcepion extends Exception {
...
}
public static Address getFromLocation() throws AddressRetrievalExcepion {
...
if (errorCondition) {
throw new AddressRetrievalExcepion("Cannot get address");
}
...
}
try {
Address addr = getFromLocation(error);
} catch (AddressRetrievalExcepion ae) {
System.out.println(ae.getMessage());
}