- Return Multiple Values in Java [5 Different Methods]
- 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
- Leave a Comment Cancel reply
- Java Tutorial
- Return Multiple Values in Java
- Return Multiple Values of the Same Type Using Array in Java
- Return Multiple Values Using a Custom Class in Java
- Return Multiple Values Using a List in Java
- Related Article — Java Method
Return Multiple Values in Java [5 Different Methods]
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.
- 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 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]); >> >
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()); >>
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]); >>
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; >>
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); >>
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
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Java Tutorial
- Set Up Java Environment
- Set Up Java on Linux
- Set up Java with BlueJ IDE
- Set up Java with VSC IDE
- Set up Java with Eclipse IDE
- Java Multiline Comments
- Java Variables
- Java Global Variables
- Java Date & Time Format
- Different Java Data Types
- Java Booleans
- Java Strings
- Java Array
- Java Byte
- Java convert list to map
- Java convert double to string
- Java convert String to Date
- Java convert Set to List
- Java convert char to int
- Java convert long to string
- Java Operators Introduction
- Java Boolean Operators
- Java Relational Operators
- Java Arithmetic Operators
- Java Bitwise Operators
- Java Unary Operators
- Java Logical Operators
- Java XOR (^) Operator
- Java Switch Statement
- Java If Else Statement
- Java While Loop
- Java For / For Each Loop
- Java Break Continue
- Java Nested Loops
- Java throw exception
- Java Try Catch
- Java Accessor and Mutator Methods
- Java main() Method
- IndexOf() Java Method
- Java ListIterator() Method
- Java create & write to file
- Java read file
- Java Parameter
- Java Argument
- Java Optional Parameters
- Java Arguments vs Parameters
- Java Arrays.asList
- Java HashSet
- Java Math
- Java HashMap vs Hashtable vs HashSet
- Java LinkedList
- Linked List Cycle
- Java List vs LinkedList
- Java ArrayList vs LinkedList
Return Multiple Values in Java
- Return Multiple Values of the Same Type Using Array in Java
- Return Multiple Values Using a Custom Class in Java
- Return Multiple Values Using a List in Java
In this tutorial, we will learn to return multiple values in Java. We cannot return more than one value from a method directly in Java, but we can use other features of Java, like Array , Pair , List etc. to achieve that.
Return Multiple Values of the Same Type Using Array in Java
We can return more than one values that are of the same data type using an array. As array stores multiple values so we can return an array from a method as in our example. Below, we create a method method1() that has a return type of String[] array of Strings. In method1() , we create three local variables and assign them with values, now we create an array of type String called array1 .
Now we set the indexes of array1 with the variables. Then we return the array using return array1 . In the main() method, we call method1() and convert it to a String using Arrays.toString() and we can see the array of all the values in the output.
import java.util.Arrays; public class MultipleObjects public static void main(String[] args) String getArray = Arrays.toString(method1()); System.out.println("Array values: " + getArray); > private static String[] method1() String name = "John Doe"; String city = "New York"; String gender = "male"; String[] array1 = new String[3]; array1[0] = name; array1[1] = city; array1[2] = gender; return array1; > >
Array values: [John Doe, New York, male]
Return Multiple Values Using a Custom Class in Java
In this example, we create a custom class, ExampleClass , with three different types of variables. In the ExampleClass constructor, we get the parameters and initialize all the variables with values. We create a method method1() that returns an instance of ExampleClass . In method1() we call the constructor of ExampleClass and pass values in it. Inside the main() function we call the method1() method that returns the object of ExampleClass .
Now we get the values using the object getValues . Notice that we can use values of different types.
public class MultipleObjects public static void main(String[] args) ExampleClass getValues = method1(); System.out.println("Value1: " + getValues.var1); System.out.println("Value2: " + getValues.var2); System.out.println("Value3: " + getValues.var3); > private static ExampleClass method1() return new ExampleClass(20, "ExampleString", true); > static class ExampleClass int var1; String var2; boolean var3; ExampleClass(int var1, String var2, boolean var3) this.var1 = var1; this.var2 = var2; this.var3 = var3; > > >
Value1: 20 Value2: ExampleString Value3: true
Return Multiple Values Using a List in Java
We make a List of all the values that we want to return in this program. In method1() , we create three variables of different data types and then call Arrays.asList() to create a List and pass all the variables in it that will make a list of Object . In main() , we call method1() and get the list of objects and print it in the console.
import java.util.Arrays; import java.util.List; public class MultipleObjects public static void main(String[] args) ListObject> getList = method1(); System.out.println("List of values: " + getList); > private static ListObject> method1() int var1 = 15; String var2 = "ExampleString"; boolean var3 = false; return Arrays.asList(var1, var2, var3); > >
List of values: [15, ExampleString, false]
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java Method
Copyright © 2023. All right reserved