112

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
  • 2
    Return array, list, set, map or your custom object containing multiple values. I have seen this same question somewhere.... let me find that. There are multiple questions on this topic: stackoverflow.com/search?q=return+multiple+values+in+java%3F Commented Dec 19, 2011 at 6:10
  • Maybe too late, but Just use java.util.AbstractMap.SimpleIEntry. Reusable, everywher since 1.6 Commented Feb 4, 2020 at 7:47
  • If you are on Java 14+, it is better in general to use a Java Record instead of a SimpleEntry for representing a pair of values. Commented Jan 30, 2021 at 14:52

3 Answers 3

93

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I would add one more point to this - keep your returned object immutable (best initialize it in a constructor and keep your fields final)
You can return an object , but if you have so many return objects in your program it makes the source code complicated. for things that are returned from a method once-of-its-kind-it-the-program better to have Tuples. like c#. darling c# its a great language
I guess there should be C# out or ref parameter equivalent in Java, otherwise I will need to create class even for returning two variables and for each function returning multiple values. If we follow this, then there will be a class for every function returning multiple values. Though using Map feels better approach now.
I would use a map or set for keeping it simple :)
Returning maps, lists or sets (to avoid returning a DTO) IMHO is an antipattern.
|
42

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 Comment

How performance efficient is this?
39

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.