Command Palette

Search for a command to run...

Back to the lesson: Topic 3.5 — Variable Arguments (varargs)
Core Java · Example 2 of 3 Java 5+

Fixed parameters plus varargs, and printf

A varargs parameter, written int... nums, lets a method accept any number of arguments of one type, including none. Inside the method it is an ordinary array, which the compiler builds for you at each call.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static int max(int first, int... rest) that returns the largest value. Requiring first means the method can never be called with zero values. Test max(4), max(4, 9, 2).

02

Write static String repeatEach(int times, String... words) that returns each word repeated times times, separated by spaces. Test repeatEach(2, "hi", "yo").

03

Write static boolean containsAll(String text, String... words) that returns true if text contains every word. Test it with "java is fun" and the words "java", "fun", then "java", "boring".

Explain it without notes

01

What does the compiler do with a call like sum(1, 2, 3) to static int sum(int... nums)?

02

Why must the varargs parameter be the last one, and why only one per method?

03

Why does Arrays.asList(new int[] {1, 2, 3}).size() return 1?

04

Given log(String) and log(String...), which does log("x") call and why?

Fixed parameters plus varargs, and printf Java 5+
Sign in to run this example in your browser.

Expected output

red, green, blue
login -> cart -> pay
[]
Asha scored 92 out of 100
avg   | 81.7