Monday, April 8, 2019

Java: return more than one result from a method


There are many ways to return multiple results from a method. Here are two of the most simple and typical ways:

public class ExampleTest {

    public void returnMultiple() {
        // Return multiple strings        String[] strArray = returnArray();
        System.out.println("Result from returnArray():");
        System.out.println(strArray[0]);
        System.out.println(strArray[1]);

        // Return boolean and string        ResultObj resultObj = returnObj();
        System.out.println("Result from returnObj():");
        System.out.println(resultObj.boolResult);
        System.out.println(resultObj.strResult);
    }

    private String[] returnArray() {
        String[] results = new String[2];

        results[0] = "result 1";
        results[1] = "result 2";

        return results;
    }

    public class ResultObj {
        public boolean boolResult;
        public String strResult;
    }

    private ResultObj returnObj() {
        ResultObj results = new ResultObj();

        results.boolResult = true;
        results.strResult = "result string";

        return results;
    }
}
 
The first way is to return an Array of the same types. We can set each item of the array inside the method. And the caller and reach them by the array.

The second way is to create a Class with multiple members. Each member holds a result. By returning an object of this Class, the caller can access the results via the Class.

The returnMultiple() method in the example will output:
Result from returnArray():
result 1
result 2
Result from returnObj():
true
result string



No comments:

 
Get This <