Multiple Return Values in Logo

Java supports multiple return values through the use of custom objects or arrays. This feature is often used to return both a result and an error status from a method.

import java.util.Arrays;

public class MultipleReturnValues {

    // This method returns an array of two integers
    public static int[] vals() {
        return new int[]{3, 7};
    }

    public static void main(String[] args) {
        // Here we use array destructuring to assign the returned values
        int[] result = vals();
        int a = result[0];
        int b = result[1];
        System.out.println(a);
        System.out.println(b);

        // If you only want a subset of the returned values,
        // you can simply ignore the unwanted values
        int c = vals()[1];
        System.out.println(c);
    }
}

When you run this program, you’ll see:

$ javac MultipleReturnValues.java
$ java MultipleReturnValues
3
7
7

In Java, we don’t have built-in support for multiple return values like in some other languages. However, we can achieve similar functionality by returning an array or a custom object. In this example, we used an array to return multiple values.

The vals() method returns an array of two integers. In the main method, we first demonstrate how to use all returned values by assigning them to separate variables. Then, we show how to use only a subset of the returned values by accessing a specific index of the returned array.

Note that Java doesn’t have a direct equivalent to the blank identifier (_) for ignoring values. Instead, we simply don’t assign the unwanted values to variables.

While this approach works, it’s often more idiomatic in Java to create a custom class to hold multiple return values, especially if they have different types or if the meaning of each value needs to be clear. This provides type safety and makes the code more readable.

Accepting a variable number of arguments is another feature available in Java; we’ll look at this next.