Multiple values via array
- Java course
- Beginner
- Lesson 80/116
- 4 min
Learn to return multiple values via an array.
Returning multiple values via an array
A method returns a single value. But if you want to pass back more than one, you can return them inside an array.
static int[] firstTwo(int a, int b) {
return new int[]{a, b};
}
int[] pair = firstTwo(3, 7);
// pair: {3, 7}Here new int[]{a, b} creates and returns a fresh two-element array. The array stays valid after the method returns; because the object lives on the heap.
Array return and usage
You assign the result of an array-returning method to a variable, then reach elements by index. The length of the array is read with .length.
int[] pair = firstTwo(3, 7);
int a = pair[0];
int b = pair[1];
System.out.println(a + " " + b);
// 3 7This is handy when several values produced during a computation need to be returned in one package. Later you will also see record types.
Practice Return min and max
Define a static int[] method called minMax; parameters int a, int b. Return a two-element array with the smaller at index 0 and the larger at index 1. In main, call minMax(9, 4) and print the result with Arrays.toString.
Starter code
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Call the method with 9 and 4, print the result
}
// Define the minMax method here
}Sample solution
static int[] minMax(int a, int b) {
if (a < b) return new int[]{a, b};
return new int[]{b, a};
}
// inside main:
System.out.println(Arrays.toString(minMax(9, 4)));Expected output
[4, 9]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match expression to meaning
| Term | Meaning |
|---|---|
new int[]{a, b} |
New two-element array |
return null; |
Returns nothing |
return new int[0]; |
Returns an empty array |
int[] pair |
Array reference variable |
2 Fill in the blank: return an array
static int[] firstTwo(int a, int b) {
return ____{a, b};
}
static int[] firstTwo(int a, int b) {
return new int[]{a, b};
}
Explanation: new int[]{a, b} creates a new array.
3 What does firstTwo(3, 7)[1] return?
int[] pair = firstTwo(3, 7);- It throws an error Correct answer
- 3
- 10
- 7
Explanation: Index 1 gives the second element.