How to return two values from a Java method?
Short answer: You can’t return two values from a Java method. Java doesn’t support multi-value returns.
Long answer: There are workarounds. Scroll down.
Returns multiple values as an array
public static int[] yourMethod(){ int number1 = 1; int number2 = 2; return new int[] {number1, number2}; } public static void main(String[] args) { int result[] = yourMethod(); System.out.println(result[0] + result[1]); }
This works only if the values you return are of same type.
Implement a generic pair object if you are sure that you need to return only two values:
public class TwoValuesReturn { public static Pair<Integer> yourMethod() { int number1 = 1; int number2 = 2; return new Pair<Integer>(number1, number2); } public static void main(String[] args) { Pair<Integer> pair = yourMethod(); System.out.println(pair.first() + pair.second()); } } class Pair<T> { private final T firstValue; private final T secondValue; public Pair(T first, T second) { firstValue = first; secondValue = second; } public T first() { return firstValue; } public T second() { return secondValue; } }
Using AbstractMap’s key and value
AbstractMap.Entry<String, Integer> map=new AbstractMap.SimpleEntry<>("Count" , 32); String name=map.getKey(); Integer value=map.getValue();
Using Collections
public static List getMultipleValues(){ List<Integer> list = new ArrayList<Integer>(); int number1 = 1; int number2 = 2; list.add(number1); list.add(number2); return list; } public static void main(String[] args) { List<Integer> numList = getMultipleValues(); }
You can also try using Map or Set to return two/multiple values from a Java method.