CodeBlanks Logo Icon CodeBlanks

Summary - Method parameters

Combine primitive, object and varargs to write a statistics function.

Summary: Method parameters

In this group you saw four aspects of parameter passing: primitive pass by value, object references, varargs and final parameters.

Primitive parameters are copied; the outside is not affected. Object parameters pass a copy of the reference; content changes affect the outside. With varargs you can accept a flexible number of arguments. final prevents reassignment.

Now you will combine these to write a small statistics function: take numbers via varargs and return min and max as an array.

Practice Statistics function

Define a static int[] method called minMax; parameter int... nums. The body should scan all elements to find the smallest and the largest; return new int[]{min, max}. In main, call minMax(4, 9, 2, 7) and print the result with Arrays.toString.

Starter code

Main.java
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    // Call the method with four values, print the result
  }
  // Define the minMax method here (varargs)
}

Sample solution

Main.java
static int[] minMax(int... nums) {
  int min = Integer.MAX_VALUE;
  int max = Integer.MIN_VALUE;
  for (int n : nums) {
    if (n < min) min = n;
    if (n > max) max = n;
  }
  return new int[]{min, max};
}
// inside main:
System.out.println(Arrays.toString(minMax(4, 9, 2, 7)));

Expected output

[2, 9]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: varargs declaration

Question
static int[] minMax(int____ nums) {
  int min = Integer.MAX_VALUE;
  int max = Integer.MIN_VALUE;
  for (int n : nums) {
    if (n < min) min = n;
    if (n > max) max = n;
  }
  return new int[]{min, max};
}
Answer
static int[] minMax(int... nums) {
  int min = Integer.MAX_VALUE;
  int max = Integer.MIN_VALUE;
  for (int n : nums) {
    if (n < min) min = n;
    if (n > max) max = n;
  }
  return new int[]{min, max};
}

Explanation: int... accepts a flexible number of arguments.

2 Match scenario to approach

Term Meaning
Flexible count of numbers varargs
Change the outer list object parameter
Prevent reassignment final parameter
Keep the primitive value safe pass by value

3 Which call is valid for a method with int... nums parameter?

  • sum(1, 2, 3)
  • sum{1, 2, 3}
  • sum([1, 2, 3]) Correct answer
  • sum(int 1, 2, 3)

Explanation: A varargs call takes comma-separated arguments.

All lessons in Beginner