Wednesday, 12 September 2018

Pop quiz answer: varargs

The answer for the VarArgs Pop Quiz.

Testcase 1 : [Ljava.lang.String;@579bb367 is not null and has length 0
Testcase 2 : args is null
Testcase 3 : [Ljava.lang.String;@1de0aca6 is not null and has length 2
     first element is null

Process finished with exit code 0

The reason for the quiz is that there's a potential NullPointerException in there, that you need to be aware of.

According to reference [1], if the argument provided is compatible with String[], it is assumed that that is what you meant. And null is always compatible with any T[].

Also interesting enough and just to drive the point home, it means that the method signatures below are identical and Java will give you a big fat warning that you defined the same method twice.

public void vars(String... args);

public void vars(String[] args);

References

[1] Oracle Java Language Spec - 15.12.4.2. Evaluate Arguments
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.4.2
Blogpost - Pop Quiz: Varargs
https://randomthoughtsonjavaprogramming.blogspot.com/2018/09/pop-quiz-varargs.html

No comments:

Post a Comment