How can a Java function return multiple values?

In Java, functions can only return one value. However, we can achieve the effect of returning multiple values through various methods.

  1. By using an array or a collection, we can store multiple values, then return that array or collection as the return value of a function. This allows us to achieve the effect of returning multiple values.
public static int[] getMultipleValues() {
    int[] values = {1, 2, 3};
    return values;
}
  1. By using custom objects, we can create an object that contains multiple values and then return this object as the output of a function.
public class MultipleValues {
    private int value1;
    private int value2;
    
    public MultipleValues(int value1, int value2) {
        this.value1 = value1;
        this.value2 = value2;
    }
    
    public int getValue1() {
        return value1;
    }
    
    public int getValue2() {
        return value2;
    }
}

public static MultipleValues getMultipleValues() {
    return new MultipleValues(1, 2);
}

This can achieve the effect of returning multiple values.

Leave a Reply 0

Your email address will not be published. Required fields are marked *