Search code examples
javafunctionreturn

Return multiple values in Java


I wrote a function in Java and I want this function to return multiple values. Except use of array and structure, is there a way to return multiple values?

My code:

String query40 = "SELECT Good_Name,Quantity,Price from Tbl1 where Good_ID="+x;
Cursor c = db.rawQuery(query, null);
if (c!= null && c.moveToFirst()) 
{
  GoodNameShow = c.getString(0);
  QuantityShow = c.getLong(1);
  GoodUnitPriceShow = c.getLong(2);
  return GoodNameShow,QuantityShow ,GoodUnitPriceShow ;
}

Solution

  • In Java, when you want a function to return multiple values, you must

    • embed those values in an object you return
    • or change an object that is passed to your function

    In your case, you clearly need to define a class Show which could have fields name, quantity and price :

    public class Show {
        private String name;
        private int price;
        // add other fields, constructor and accessors
    }
    

    then change your function to

     public  Show  test(){
          ...
          return new Show(GoodNameShow,QuantityShow ,GoodUnitPriceShow) ;