6

While working with Java Applications, I feel most of the times one question : Why Java doesn't support multiple return values of methods?

I know that people who designed Java, must have done thinking about this topic but I didn't get any answer or particular reason while thinking myself.

Vishal Zanzrukia
  • 4,902
  • 4
  • 38
  • 82

2 Answers2

2

If all the values are of the same type, you can just return an array of them:

public String[] myMethod{} {}

If they are not, they you have multiple options:

The ugly one is to cast everything into an Object and return either:

public Object[] myMethod{} {}

or

public List<? extends Object> myMethod() {}

The problem with these implementations is you really don't know what's what in the object/list unless you look at the method implementation. So it can be a shortcut if you know noone else is going to use this.

There's cleaner but a bit more time consuming. But it's usually a good practice because carries more information:

Say you want to return two values, an int and a String. You need to design an object that represents those two (or more values):

public class MyResponse {
    public String myString;
    public int myInt;
}

And return an instance of MyResponse. Note that here I made the attributes public. There are multiple schools of thoughts around this. Some will prefer to make them private and add getter/setter methods. That's homework for you.

mprivat
  • 21,582
  • 4
  • 54
  • 64
  • 6
    +0: Good info, but now not directly related to question - shows how to return multiple items in single result rather than "why single result". Consider also providing "Why single return value" portion of answer too. Maybe "why no `out`/`ref` result like in C++"? – Alexei Levenkov May 23 '14 at 06:44
  • Point I was trying to make is, "yes it does return multiple values". Probably not as elegantly as Haskell, Lisp or even Python, but it does. Therefore the question is moot in my opinion. – mprivat May 23 '14 at 06:57
-2

Conceptually Java method should acomplish only one action on data and return concrete result. If you could not decide what should return your method this is a cause of bad OOP design of the class.

If you just want to return a several objects (one type of objects) from method you should use collections or arrays as @mprivat said.

Artem SE
  • 1
  • 2