Multiple Return Values in Java
Java has built-in support for returning multiple values from a method using custom objects or arrays. This feature is often used to return both result and error values from a method.
To run the program, compile and execute it using the javac
and java
commands:
In Java, we don’t have direct 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 demonstrate how to use these returned values:
- We first capture all returned values into an array and then assign them to individual variables.
- We then show how to access only a subset of the returned values by directly accessing the array element we’re interested in.
Note that Java doesn’t have a built-in way to ignore values (like the blank identifier _
in some other languages), so we simply don’t assign the values we don’t need.
This approach provides a way to return and handle multiple values from a method, which can be useful in various scenarios, such as returning both a result and an error status.