0

Say I have a java function as follows,

public static int my(int a, int b)
{

    int c = a + b;
    return c;

    String d = "Some Data";
    return d;

    float f = a/b;
    return f
}

So, how do I get the 3 return values separately?

all the values are of different data types.

I've seen this question and this question but couldn't understand properly.

Community
  • 1
  • 1

6 Answers6

4

any function can only return one value. What you can do is to create an objet containing all your answers and return this object.

class ResultObject
{
   public int c;
   public int d;
   public int e;
   public int f;
}

in your function white

public static ResultObject my(int a, int b)
{
ResultObject resObject = new ResultObject();
resObject.c = a + b;

resObject.d = a*b;

resObject.e = a-b;

resObject.f = a/b;
return resObject;
}

You can return only one value. You have to make that value to "contain" other values.

user1354033
  • 203
  • 2
  • 10
1

return array of int.. e.g. int[]...

public static int[] my(int a, int b) {
    int res[] = new int[4];

    int c = a + b;
    res[0] = c;

    int d = a * b;
    res[1] = d;

    int e = a - b;
    res[2] = e;

    int f = a / b;
    res[3] = f;

    return res;
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
niiraj874u
  • 2,180
  • 1
  • 12
  • 19
1

There are two ways.

  1. If you returning uniform values, e.g. hundred values for temperature over a period of time - use arrays.
  2. If values are non-uniform, e.g. first name, last name and age - introduce a new class.

Reason for this is that Java is a strongly-typed programming language. Wanna describe a new data structure - write a new class.

Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
0

You can try something like this

  public static int[] my(int a, int b) { // use an array to store values
    int[] arr = new int[4];
    int c = a + b;
    arr[0] = c;

    int d = a * b;
    arr[1] = d;

    int e = a - b;
    arr[2] = e;

    int f = a / b;
    arr[3] = f;

    return arr; // return values 
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • Please check my edit, what to do if the return types are of different data types? –  Apr 21 '14 at 09:21
0

You can return only one element but the element may be array or list.you may return list of values.(some exercise). I hope this may bring some solution.

Sanjay Rabari
  • 2,091
  • 1
  • 17
  • 32
0
public class DataStorage{
         private int a;
         private String data;
         private float f;

         public DataStorage(int a, String data, float f){
             this.a = a;
             this.data = data;
             this.f = f;

         }

         /* standard get/set method. */
     }

    public static DataStorage my(int a, int b)
    {

       int c = a + b;


       String d = "Some Data";


       float f = a/b;


        DataStorage dataStorage = new DataStorage(c,d,f);
        return dataStorage;
    }
root
  • 1,573
  • 3
  • 23
  • 38