All topics
library
intermediate

Varargs & Heap Pollution

Understand variable-length arguments, their array backing, and the safety concerns with generic varargs.

Varargs (variable arguments) let a method accept zero or more arguments of the same type. Declared with Type... syntax, the compiler converts them to an array at the call site.

Varargs = a box that can hold any number of items. But if the box label says 'Strings Only' (generic), the actual box material is 'Any Object' (erasure) — someone could sneak in an Integer.

Key Concepts

1
Key rules: - Only one varargs parameter per method, and it must be the last parameter. - The compiler creates an array: print(1, 2, 3) becomes print(new int[]{1, 2, 3}). - You can pass an explicit array instead of individual arguments. - Varargs have the lowest priority in overload resolution.
2
Heap pollution occurs when a variable of a parameterized type refers to an object that isn't of that type. This is particularly dangerous with generic varargs because Java creates a raw Object[] to hold the arguments (due to type erasure), even if the varargs parameter is declared as T....
3
@SafeVarargs annotation on a final/static/private method tells the compiler 'I promise this method doesn't do anything unsafe with the varargs array.' This suppresses the heap pollution warning. Only use it when you truly only read from the array — never store it or expose it.
4
Common uses: List.of(E...), String.format(String, Object...), Collections.addAll(Collection, T...).