Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java method does not support multiple return values? [duplicate]

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.

like image 446
Vishal Zanzrukia Avatar asked May 23 '14 06:05

Vishal Zanzrukia


People also ask

Can Java methods have multiple return values?

Java doesn't support multi-value returns.

Can you have multiple return values?

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values.

How u will return multiple values in a method?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.


1 Answers

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.

like image 98
mprivat Avatar answered Sep 21 '22 20:09

mprivat