Is varargs array creation lazy?

Consider the following code:

void someMethod(Object... varargParam){
    if(someCondition){
        doSomethingWith(varargParam);
    }
}

If someCondition resolves to false, varargParam is unused. Will the Object array still be created or is this creation postphoned to the first use?

Answer

varargParam is created when the call happens, also if not used in the method itself.

From JLS 15.14.2:

If the method being invoked is a variable arity method m, it necessarily has n > 0 formal parameters. The final formal parameter of m necessarily has type T[] for some T, and m is necessarily being invoked with k ≥ 0 actual argument expressions.

Leave a Reply

Your email address will not be published. Required fields are marked *