How to Return Multiple Values? [Duplicate]

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
}
Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.