Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values from a method in Java

I have written a method in Java which returns 2 values. 1st Count of result which is of int type and 2nd if the method is success true/false boolean type. How can I return both values? So that if the method is a success then only proceed.

Sample code:

public static void main(String args[])
{
    int count = 0;
    boolean status = false;
    //count = retrieveData(); Current code working but captures only 1 values at a time i.e. Count not the status

    /* Expected Code

    if (status == true)  // where status and count is returned from retrieveData method
    {
        count = retrieveData();
        System.out.println("Status is true so can proceed");
    }

    else
        System.out.println("Status is not true so don't proceed");
    */
}





public static int retrieveData() throws  Exception 
    {

        boolean success = false;
        String query = "SELECT Count(1) FROM Account";
        int totalCount=0;
        ResultSet rsRetrieve = null;
            Statement stmt = null;
            stmt = conn.createStatement();
            rsRetrieve = stmt.executeQuery(query);
            while (rsRetrieve.next())
            {
                totalCount= rsRetrieve.getInt(1);
                System.out.println("totalCount : "+totalCount);
            }


        success = true;
        return totalCount; // current working code but returns only 1 value i.e. Count not status

        /*   Expected

        return success + totalCount

        */
    }
like image 572
Vikas J Avatar asked Oct 18 '25 06:10

Vikas J


1 Answers

There are different ways to retun the Multiple values from a method some of the best approaches that i use are:

1- Make Class for the datatypes that you want to return for example you want to return two Strings make class like this:

public class myType {
            String a;
            String b;

            public String getA() {
                return a;
            }

            public void setA(String _a) {
                a = _a;
            }
            //And All other geter setters
        }

and make return type of your method to the above class.

2- Return Map with key value pairs
3- Make Interface and call Abstract method from where you want to return the values (You have to implement the interface in the class where you want to receive the values) Hope This will give you rough idea to move forword

like image 184
Software Developer Avatar answered Oct 20 '25 20:10

Software Developer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!