Can a Java method return multiple types?

Java does not support multiple return values. However, sometimes it is required to return multiple values. For that, we can use the following solutions.

Case 1: If all of the returned values are the same

If all the values that have to be returned are the same, then we can use an array. For example, two numbers are given, and it is required to perform the addition, subtraction, multiplication and division on these numbers. In such a scenario, we can use an array. Observe the following program.

FileName: ReturnMultipleValues.java

Output:

The sum of numbers 6 and 3 is: 9
The difference of numbers 6 and 3 is: 3
The multiplication of numbers 6 and 3 is: 18
The division of numbers 6 and 3 is: 2

Complexity Analysis: Since the program is using a for-loop for computing the sum of elements, the time complexity of the program is O(n), where n is the total number of elements present in the array. The space complexity of the program is constant, i.e., O(1).

Case 2: If we have to return two values of different types

In case we have the two values of the different types, we can use Pair.

FileName: ReturnMultipleValues1.java

Output:

Case 3: If we have to return more values of different types

In that case, we can use a class. Observe the following program.

FileName: ArithmeticOperation.java

Output:

Statement: Performing Arithmetic Operation
The Multiplication of the numbers 29 and 20 is: 580
The Division of the numbers 29 and 20 is: 1.45
The Addition of the numbers 29 and 20 is: 49



You can return only one value in Java. If needed you can return multiple values using array or an object.

Example

In the example given below the calculate() method accepts two integer variables performs the addition subtraction, multiplication and, division operations on them stores the results in an array and returns the array.

public class ReturningMultipleValues {
   static int[] calculate(int a, int b){
      int[] result = new int[4];
      result[0] = a + b;
      result[1] = a - b;
      result[2] = a * b;
      result[3] = a / b;
      return result;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of a: ");
      int a = sc.nextInt();
      
      System.out.println("Enter the value of b: ");
      int b = sc.nextInt();
      int[] result = calculate(a, b);
      
      System.out.println("Result of addition: "+result[0]);
      System.out.println("Result of subtraction: "+result[1]);
      System.out.println("Result of multiplication: "+result[2]);
      System.out.println("Result of division: "+result[3]);
   }
}

Output

Enter the value of a:
20
Enter the value of b:
10
Result of addition: 30
Result of subtraction: 10
Result of multiplication: 200
Result of division: 2

Can a Java method return multiple types?

Updated on 30-Jul-2019 22:30:20

  • Related Questions & Answers
  • How can we return multiple values from a function in C#?
  • How to return multiple values to caller method in c#?
  • How can we return multiple values from a function in C/C++?
  • Can the main method in Java return a value?
  • How to return 2 values from a Java method
  • Can we return this keyword from a method in java?
  • How do we return multiple values in Python?
  • Can we change return type of main() method in java?
  • Find and return array positions of multiple values JavaScript
  • Provider values() method in Java
  • How can we return null from a generic method in C#?
  • Can a try block have multiple catch blocks in Java?
  • Can we fetch multiple values with MySQL WHERE Clause?
  • How to return an array from a method in Java?
  • Can we inherit a final method in Java?

  • Return Multiple Values in Java
    • Return an Array of specific type or object
    • Return using the Pair class of util Package
    • Return a String object with a delimiter
    • Return a Custom class object
    • Return using a Collection object List
  • Summary
  • References

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

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

Can a method have multiple return types in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.

How can I return multiple data types in Java?

If all the values that have to be returned are the same, then we can use an array. For example, two numbers are given, and it is required to perform the addition, subtraction, multiplication and division on these numbers. In such a scenario, we can use an array. Observe the following program.

Can a Java method return more than one object?

Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.

Can a function return multiple data types?

If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.