How to return multiple values in Java using the “return” statement?
In Java, a method can only return one value. However, multiple values can be returned in different ways, such as:
- Using an array or a collection: multiple values can be stored in an array, list, or other collection, and then this array or collection can be returned as the method’s result.
public static List<Integer> getMultipleValues() {
List<Integer> values = new ArrayList<>();
values.add(1);
values.add(2);
values.add(3);
return values;
}
- You can use custom objects by defining an object that contains multiple values, and then returning that object as the return value of a method.
public class CustomObject {
private int value1;
private int value2;
public CustomObject(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int getValue1() {
return value1;
}
public int getValue2() {
return value2;
}
}
public static CustomObject getMultipleValues() {
return new CustomObject(1, 2);
}
- You can utilize a Map to store multiple key-value pairs, and then return this Map as the method’s result.
public static Map<String, Integer> getMultipleValues() {
Map<String, Integer> values = new HashMap<>();
values.put("value1", 1);
values.put("value2", 2);
return values;
}
Here are some common methods that can be used to return multiple values. Choose the appropriate way based on specific needs to return multiple values.