liveBook · Manning

Variable arity call

As explained in 100 Java Mistakes and How to Avoid Them

A variable arity call is a method invocation that supplies an arbitrary number of arguments to a variable arity parameter.

A variable arity call supplies any number of arguments to a final variable arity parameter. Java usually wraps flat arguments into an array, but an explicitly passed array may be used unchanged. section 2.9 section 2.9.1

Flat arguments and explicit arrays

static void printAll(Object... data) { /* ... */ } printAll("Hello", "World"); printAll(new Object[]{"Hello", "World"}); Both calls provide the method with the same array contents. section 2.9.1

A single argument becomes ambiguous when its declared type is Object: even if it holds an array at runtime, compilation wraps it as one element. Passing null is also dangerous because null can be treated as the array reference itself. section 2.9.1 section 2.9.1

Make null intent explicit

printAll((Object)null); // an array containing null printAll((Object[])null); // a null array reference section 2.9.1

Avoid placing a conditional expression directly inside a variable arity call. If one branch is a String and the other an Object[] array, the expression becomes Object and receives an extra array wrapper. section 2.10

Reduce ambiguity with these practices:

  • Prefer an if statement over a conditional expression inside a variable arity call. section 2.10
  • Cast arguments when you need to distinguish an element from an array reference. section 2.9.1
  • Use static-analysis warnings, including IntelliJ IDEA’s Suspicious Ternary Operator in Varargs Method Call inspection, as a review aid. section 2.10

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains automatic wrapping, explicit arrays, declared-type overload behavior, null handling, and conditional-expression typing.
Examples
Uses printAll, Object-valued arrays, null casts, formatted printing, and a conditional default argument.
What it assumes
Assumes Java method-call knowledge while teaching variable arity parameters, array wrapping, declared types, and null behavior.
What you can do after
Diagnose ambiguous calls and prevent unintended array wrapping by choosing explicit argument types and clearer control flow.
How it connects
Connects variable arity calls with arrays, conditional expressions, compile-time types, null, method invocation, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.