- 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
- Как вернуть два значения из метода java
- Как вернуть несколько значений из функции java
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
Как вернуть два значения из метода java
В Java мы не можем вернуть два значения из метода, только одно. Но можем возвратить массив, список или мапу, содержащие нужные нам данные. Например :
public static ListInteger> func() int a = 1; int b = 2; return List.of(a, b); >
Также можно описать класс, содержащий несколько переменных разных типов, и вернуть объект этого класса.
public class MyClass // необходимо вернуть число и строку private int n; private String str; public MyClass(int n, String str) // конструктор this.n = n; this.str = str; > public int getN() return n; > // геттеры public String getStr() return str; > > public static MyClass func() // метод return new MyClass(5, "Ivan"); // создаем объект нашего класса и возвращаем его > MyClass x = func(); // получаем объект нашего класса System.out.println(x.getN() + " " + x.getStr()); // => 5 Ivan
Как вернуть несколько значений из функции java
В Java мы не можем вернуть несколько значений из метода, только одно. Но мы можем возвратить массив, список или мапу, содержащие нужные нам данные. Например :
public static ListInteger> func() int a=1, b=2, c=3; return List.of(a, b, c); >
Также можно описать класс, содержащий несколько переменных разных типов, и вернуть объект этого класса.
// пусть нам необходимо вернуть число, строку и логическое значение class MyClass private int age; private String name; private boolean isMan; public MyClass(int age, String name, boolean isMan) this.age = age; this.name = name; this.isMan = isMan; > public int getAge() return age; > public String getName() return name; > public boolean getIsMan() return isMan; > >
Получение объекта с несколькими параметрами из метода :
public class App public static void main(String[] args) throws Exception MyClass x = func(); // получаем объект нашего класса System.out.println(x.getAge() + " " + x.getName() + " " + x.getIsMan()); // => 20 Ivan true > // метод, возвращающий несколько значений в виде объекта public static MyClass func() // создаем объект нашего класса и возвращаем его return new MyClass(20, "Ivan", true); > >