Multiple Return Values in Fortress

Java has built-in support for returning multiple values from a method using custom objects or arrays. This feature can be used to return both result and error values 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 the returned array and assign its 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 ignore some values by not assigning them
        int c = vals()[1];
        System.out.println(c);
    }
}

To run the program, compile and execute it:

$ javac MultipleReturnValues.java
$ java MultipleReturnValues
3
7
7

In Java, we don’t have direct support for multiple return values like in some other languages. Instead, we can use arrays or custom objects to achieve similar functionality. 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 demonstrate how to use these returned values:

  1. First, we assign the entire array to a variable and then extract individual values.
  2. Then, we show how to access only a specific value from the returned array if you don’t need all values.

Note that Java doesn’t have a direct equivalent to the blank identifier (_) used in some other languages to ignore values. Instead, you simply don’t assign the values you don’t need.

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