Return Multiple Values in Java [5 Different Methods]


Java Examples

Return Multiple Values in Java

In Java, the methods can return only one value at a time. In other words, Java doesn't support the return of multiple values from a method directly. However, in some applications it is required to return multiple value from a function. In order to achieve this goal, we can use some other features of Java like an Array, a Pair, a List, etc. Depending on the type and nature of data, we need to choose an appropriate approach to accomplish this task. We can use any of the five shown approaches as per the program requirement to return multiple values in Java.

  1. Return an array of specific type or object
  2. Return using the Pair class of util package
  3. Return a String object with a Delimiter
  4. Return a Custom class object
  5. Return using a Collections object - List

 

Return an Array of specific type or object

In order to return multiple values in Java, we can use an array to stores multiple values of the same type. However, we can use this approach only if all the values to be returned are of the same type. This is the simplest approach to return both primitive type data as well as reference data types.
Example :
In the example, we will compute the factorial of all numbers till the given number and returns its results in the form of an array.

class Main {
    static int[] factorial(int n) {
        // Declaring variable and Initializing
        int[] result = new int[n];
        int i = 0, j, fact;

        for (i = 1; i & lt; = n; i++) {
            fact = 1;
            // Computing factorial of ith element 
            for (j = i; j & gt; 1; j--) {
                fact = fact * j;
            }
            // Storing factorial result in an array
            result[i - 1] = fact;
        }
        // returning array of elements 
        return result;
    }

    // Driver method 
    public static void main(String[] args) {
        int[] res = factorial(5);
        // printing the results
        for (int i = 0; i & lt; 5; i++) {
            System.out.println("Factorial of " + (i + 1) + " is " + res[i]);
        }

    }
}

Output

Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

 

Return using the Pair class of util Package

From Java 8 onwards, We can use this approach to return multiple values in Java. Here, we will represent the name-value pairs using the Pair class available in the javafx.util package. In other words, if we need to return exactly two values from a function, we can use this approach.

Example :
In this example, we will return a college code along with a college name in form of key-value pair from the getCode function.

// Returning a pair of values from a function - Available from Java 8 Onwards
// Importing a package
import javafx.util.Pair;

class Main {
    // Function that returns key-value pair
    public static Pair getCode() {
        return new Pair(112, "Indian Institute of Technology, Kanpur");
    }

    // Return multiple values from a method in Java 8 
    public static void main(String[] args) {
        Pair p = getCode();
        System.out.println(p.getKey() + " " + p.getValue());
    }
}

Output

112 Indian Institute of Technology, Kanpur

 

Return a String object with a delimiter

In this approach, we will return multiple values by constructing the result as a single string such that a delimiter separates the different values. On the other hand, after receiving the string we have to split it using the same delimiter. However, this approach is not so efficient as we may need to convert the string to a numeric value for certain data value.

Example :
In the example, the getData function returns multiple values as a string separated by the delimiter "-". On the other hand, we split the string using the same delimiter to extract the values.

class Main {
    // Function that returns multiple values as a string and a delimiter
    public static String getData() {
        // Initializing variables
        String name = "John";
        String location = "Mumbai";
        int meritno = 1522;
        long salary = 100000;
        // Sign "-" act as a delimiter
        return name + "-" + location + "-" + meritno + "-" + salary;
    }

    // Return multiple values from a method in Java
    public static void main(String[] args) {
        // Calling a function and spliting the return values into String array
        String st[] = getData().split("-");

        // Printing the results
        for (int i = 0; i & lt; st.length; i++)
            System.out.println(st[i]);
    }
}

Output

John
Mumbai
1522
100000

 

Return a Custom class object

This is the commonly used approach if we want to return multiple values of different types in Java. We simply encapsulate all returned types into a class and then return an object of that class. Such a class will be a simple java class with a public member variables and a public constructor if needed.

Example : In this example, we will define a Student class consisting of class variables. Thereafter, we will define a method getdata to access the variables of student class and assign values to them through the object. We will then pass this object to the putdata function in order to display the values of class variables of the student class. Note that the class variable of Student class must be public.

public class Main {

    public Student getdata() {
        // Creating Student object and assigning values
        Student s = new Student();
        s.name = "John";
        s.location = "Mumbai";
        s.meritno = 1522;
        return s;
    }
    // Function that displays the data
    public void putdata(Student s) {
        System.out.println("Name of the student " + s.name);
        System.out.println("Location of the student " + s.location);
        System.out.println("Merit No of the student " + s.meritno);
    }

    // Main function
    public static void main(String args[]) {
        Main m = new Main();
        Student s = m.getdata();
        m.putdata(s);

    }

    // Defining Student class
    class Student {
        // class variables
        public String name;
        public String location;
        public int meritno;
    }
}

Output

Name of the student John
Location of the student Mumbai
Merit No of the student 1522

 

Return using a Collection object List

This approach to return multiple values in Java is an alternative to returning an array. Here, we will return a List Interface of a Collection object. The collections framework consists of a wide variety of a classes and an interfaces.

import java.util.Arrays;
import java.util.List;

class Main {
    // Function that returns multiple values in Java
    public static List getData() {
        // Declaring variable and Initializing
        String name = "John";
        String location = "Mumbai";
        int meritno = 1522;
        long salary = 100000;
        // Returning as a list 
        return Arrays.asList(name, location, meritno, salary);
    }

    // Return multiple values from a method in Java
    public static void main(String[] args) {
        // Calling Function
        List s = getData();

        // Printing results
        System.out.println("Data obtained : " + s);
    }
}

Output

Data obtained : [John, Mumbai, 1522, 100000] 

 

Summary

The knowledge of returning multiple values in Java is very useful while working on real time applications. In this tutorial, we covered five different approaches to return multiple values in Java. As per the requirement of an application, we can choose an appropriate approach to return the values. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on returning multiple values from a function in Java.

 

References

Pair class of util Package
List Interface

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment