Java doesn’t support multi-value returns. We can use following solutions to return multiple values.
If all returned elements are of same type
We can return an array in Java. Below is a Java program to demonstrate the same.
Sum = 150 Sub = 50
If returned elements are of different types
Using Pair (If there are only two returned values)
We can use Pair in Java to return two values.
If there are more than two returned values
We can encapsulate all returned types into a class and then return an object of that class.
Let us have a look at the following code.
Multiplication = 200 Division = 0.5 Addition = 30
Returning list of Object Class
[Geek, 35, M]
This article is contributed by Twinkle Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Passing and Returning Objects in Java
- Java and Multiple Inheritance
- Java Multicasting (Typecasting multiple times) Puzzle
- Java | CDMA (Code Division Multiple Access)
- Execute main() multiple times without using any other function or condition or recursion in Java
- Assigning values to static final variables in Java
- Default array values in Java
- Hashmap methods in Java with Examples | Set 2 (keySet(), values(), containsKey()..)
- Assigning long values carefully in Java to avoid overflow
- Sorting a 2D Array according to values in any given column in Java
- Map Values() Method in Java With Examples
- Stream.of(T... values) in Java with examples
- ChronoUnit values() method in Java with Examples
- Iterating over Enum Values in Java
- HashMap values() Method in Java
- TreeMap values() Method in Java
- EnumMap values() Method in Java
- WeakHashMap values() Method in Java
- IdentityHashMap values() Method in Java
- Check if a string contains only alphabets in Java using ASCII values