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.
class Test {
static int [] getSumAndSub( int a, int b)
{
int [] ans = new int [ 2 ];
ans[ 0 ] = a + b;
ans[ 1 ] = a - b;
return ans;
}
public static void main(String[] args)
{
int [] ans = getSumAndSub( 100 , 50 );
System.out.println( "Sum = " + ans[ 0 ]);
System.out.println( "Sub = " + ans[ 1 ]);
}
}
|
Output:
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.
import javafx.util.Pair;
class GfG {
public static Pair<Integer, String> getTwo()
{
return new Pair<Integer, String>( 10 , "GeeksforGeeks" );
}
public static void main(String[] args)
{
Pair<Integer, String> p = getTwo();
System.out.println(p.getKey() + " " + p.getValue());
}
}
|
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.
class MultiDivAdd {
int mul;
double div;
int add;
MultiDivAdd( int m, double d, int a)
{
mul = m;
div = d;
add = a;
}
}
class Test {
static MultiDivAdd getMultDivAdd( int a, int b)
{
return new MultiDivAdd(a * b, ( double )a / b, (a + b));
}
public static void main(String[] args)
{
MultiDivAdd ans = getMultDivAdd( 10 , 20 );
System.out.println( "Multiplication = " + ans.mul);
System.out.println( "Division = " + ans.div);
System.out.println( "Addition = " + ans.add);
}
}
|
Output:
Multiplication = 200
Division = 0.5
Addition = 30
Returning list of Object Class
import java.util.*;
class GfG {
public static List<Object> getDetails()
{
String name = "Geek" ;
int age = 35 ;
char gender = 'M' ;
return Arrays.asList(name, age, gender);
}
public static void main(String[] args)
{
List<Object> person = getDetails();
System.out.println(person);
}
}
|
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 review-team@geeksforgeeks.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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Sep, 2018
Like Article
Save Article