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.
Java doesn't support multi-value returns.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With