How to return multiple values from a method in Java?

Member

by kennedi , in category: Java , 2 years ago

How to return multiple values from a method in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emerald , 2 years ago

@kennedi  You can declare an array of values to return multiple values:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Random;

class Main {
    public static int[] get_random_numbers(){
        Random rand = new Random();

        return new int[]{rand.nextInt(), rand.nextInt(), rand.nextInt()};
    }

    public static void main(String[] args) throws Exception {
        int[] random_numbers = get_random_numbers();

        for (int i = 0; i < random_numbers.length; i++){
            System.out.println(random_numbers[i]);
        }

        // Example Output : 
        //-279229926
        // -1161088692
        // 1721970958
    }
} 


by august.kutch , a year ago

@kennedi 

In Java, a method can return only one value at a time. To return multiple values, you can use an array or an object to store the values and return that. Another option is to create a custom class to hold the multiple values and return an instance of that class from the method.


Another way is to use Tuple, which is not present in the core Java library, but you can use external libraries like "javatuples" which provide Tuple classes


For example:

1
2
3
4
5
class Example {
  public static Tuple2<String, Integer> getValues() {
    return Tuple.of("hello", 1);
  }
}


You can also use the java.util.Map interface to return multiple values by name, for example:

1
2
3
4
5
6
7
8
class Example {
  public static Map<String, Object> getValues() {
    Map<String, Object> map = new HashMap<>();
    map.put("value1", "hello");
    map.put("value2", 1);
    return map;
  }
}


You can also use the java.util.Pair<L,R> which is available from android support library, for example

1
2
3
4
5
class Example {
  public static Pair<String, Integer> getValues() {
    return new Pair<>("hello", 1);
  }
}


All of the above options allow you to return multiple values from a single method in Java.