How to return multiple values? [duplicate]

Is it possible to return two or more values from a method to main in Java? If so, how it is possible and if not how can we do?

3

3 Answers

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.

6

You can do something like this:

public class Example
{ public String name; public String location; public String[] getExample() { String ar[] = new String[2]; ar[0]= name; ar[1] = location; return ar; //returning two values at once }
}
1

You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg

public class MyResult { int returnCode; String errorMessage; // etc
}
public MyResult someMethod() { // impl here
}

You Might Also Like