0

Is it possible to return more than one value in java function? Like ,

public void retTest() {
    return (30,40,50);
}

//From Caller fun 
int a,b,c;
(a,b,c) = retTest();
initramfs
  • 8,275
  • 2
  • 36
  • 58
badri.coder
  • 147
  • 1
  • 1
  • 7
  • 2
    No. Java doesn't have tuple like python has. You need to use a `List` or an array. – Rohit Jain Feb 09 '14 at 11:16
  • 2
    put those things in an object.. and return the object... – TheLostMind Feb 09 '14 at 11:16
  • 2
    @RohitJain Although returning a tuple doesn't exactly count as returning more than one value. The only language I know of which truly has multi-return semantics is Common Lisp. The values are returned all in the same way: on the call stack. – Marko Topolnik Feb 09 '14 at 11:23
  • As far as I can see, OP isn't even asking to return multiple values literally; he's just looking for some syntactic sugar like tuple literals and destructuring binds. Those *could* come to Java if they were considered really essential. – Marko Topolnik Feb 09 '14 at 11:27
  • 1
    Also, if the return type is `void` it will not return even a single value. – SJuan76 Feb 09 '14 at 11:27
  • @MarkoTopolnik hmm. Yeah you're right. :) – Rohit Jain Feb 09 '14 at 11:27

4 Answers4

3

No its not possible. But you can use return an object which encapsulates all your data.In that way coding,debugging and data extraction becomes easier as well as code enhancability is greatly increased..

such as :-

class Resut{

int a,b,c;
}

retTest()
{
return new Result();
}
Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
1

You can do so by returning a List of some kind (like an ArrayList), or some other collection, or your own custom object that contains the fields, or an array.

For just a tuple result like that, an array would be a sensible option.

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
1

No you can't return many parameters in Java, even the out Keyword is not supported, you should create a new type that may contain your values and return it.

Class ReturnObject
{
    //Fields you want to return here
    public ReturnObjectConstructor(InterParamtersHere)
    {
       // Initialize your fields here
    }

}

Public ReturnObject YourMethod()
{
    ReturnObject returnObject = new ReturnObject(parameterHere)
    return returnObject;
}
AymenDaoudi
  • 7,811
  • 9
  • 52
  • 84
0

your method definition can be as follows

public List<Integer> retTest() 

where you can return ArrayList of integer values as follows

        List<Integer> values = new ArrayList<Integer>() {
            {
                add(536);
                add(85);
                add(50);
                add(45);
            }
        };
return values;
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86