I've got the following code:
public static void varargsMethod(String ... strings) {
if (strings != null && strings.length != 0) {
for (String s : strings) {
System.out.println(s);
}
} else {
System.out.println("Hello (string free) world!");
}
}
public static void main(String[] args) {
varargsMethod(null);
varargsMethod((String[]) null);
varargsMethod((String) null);
varargsMethod();
}
I wonder why the first invocation with null as the argument generates a warning with the hint, that an explicit cast is needed. From the answers on this question it is not clear for me, why this cast is needed. The first two invocations work and produce the same result, while the third produces "null". I explicitly want the behaviour of the first two invocations.
Shouldn't null be always valid (and automatically casted) for reference types and arrays? I don't see, why the type information is important in this case.
Edit: Updated the code with a variant with no arguments at all. I definetly need to differ between the three cases (no array and empty array handled in the same way; array with null value in another). I wonder if there's a better way than checking for null and empty array.