Oct 01

You have a few options, either return them in an array, or a Map or use another class to store the values and return that.


/** Use an array to return two value */

public int[] methodReturningTwoInts()
{
   int a = getA();
   int b = getB();
   return new int[] { a, b };
}

/** Use a Map to return two value */

public Map<String, Integer> methodReturningTwoInts()
{
   int a = getA();
   int b = getB();
   Map<String, Integer> result = new HashMap<String, Integer>();
   result.put("a", a);
   result.put("b", b);
   return result;
}

/** Use a object to return two values */

public MyBean methodReturningTwoValues()
{
   int a = getA();
   String b = getB();
   return new MyBean(a, b);
} 

written by objects \\ tags:


2 Responses to “How can I return more than one value from a Java method?”

  1. Vincenzo Says:

    One follow up question…I tried the third solution where you return the object and I’m getting an error message

    Return.java:18: cannot find symbol
    symbol : class MyBean
    location: class Return
    public MyBean getEmployee1()
    ^
    Return.java:22: cannot find symbol
    symbol : class MyBean
    location: class Return
    return new MyBean ( fname, lname );

    I’m trying to return two strings

    thanks in advance for your help

  2. objects Says:

    you need to make sure your MyBean class is available in your compile classpath

Leave a Reply