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

        */
    }

5 Answers

2
user3401493 On

You can create a custom java object as follows

public class Result {

   private boolean success;
   private int totalResults;

   public Result(boolean success, int totalResults){
    this.success = success;
    this.totalResults = totalResults;
   }
   public boolean getSuccess(){
     return this.success;
   }

   public boolean getTotalResults(){
       return this.totalResults;
   }

}
0
Tim Biegeleisen On

I recommend sticking with your current general approach and not trying to return two pieces of information from your method. Your method signature throws an exception, and one possible way to handle this would be to have your method throw an exception when something goes wrong. Otherwise, it means that the count query did run, and some count would be returned. But, you should probably have a try catch block surrounding your JDBC code:

public static int retrieveData(Connection conn) throws Exception {
    Statement stmt = null;
    int totalCount = 0;

    try {
        String query = "SELECT COUNT(*) FROM Account";

        ResultSet rsRetrieve;
        stmt = conn.createStatement();
        rsRetrieve = stmt.executeQuery(query);

        if (rsRetrieve.next()) {
            totalCount = rsRetrieve.getInt(1);
            System.out.println("totalCount : " + totalCount);
        }
    }
    catch (SQLException e) {
        System.out.println(e.getMessage());
        threw new Exception("something went wrong");
    }
    finally {
        if (stmt != null) {
            stmt.close();
        }

        if (conn != null) {
            conn.close();
        }

    }

    return totalCount;
}

So the pattern being used here is that if something goes wrong, there is no count, and the caller gets an exception. Otherwise, if no exception happens, then some count would be returned.

0
Thorbjørn Ravn Andersen On

You can’t but you can create a bean class for holding multiple objects.

If this is for programmatic error handling you may want to have a look at Optional (standard) or Either (vavr) to handle multiple outcomes

0
hqt On

You can use Java Pair

import javafx.util.Pair;

public Pair retrieveData(int a, int b) {
   return new Pair(a, b);
}

Pair p = retrieveData(1,2);
int a = p.getKey();     // 1
int b = p.getValue();   // 2
2
Software Developer On

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