Why null cast a parameter? [duplicate]

If doSomething is overloaded, you need to cast the null explicitly to MyClass so the right overload is chosen:

public void doSomething(MyClass c) {
    // ...
}

public void doSomething(MyOtherClass c) {
    // ...
}

A non-contrived situation where you need to cast is when you call a varargs function:

class Example {
    static void test(String code, String... s) {
        System.out.println("code: " + code);
        if(s == null) {
            System.out.println("array is null");
            return;
        }
        for(String str: s) {
            if(str != null) {
                System.out.println(str);
            } else {
                System.out.println("element is null");
            }
        }
        System.out.println("---");
    }

    public static void main(String... args) {
        /* the array will contain two elements */
        test("numbers", "one", "two");
        /* the array will contain zero elements */
        test("nothing");
        /* the array will be null in test */
        test("null-array", (String[])null); 
        /* first argument of the array is null */
        test("one-null-element", (String)null); 
        /* will produce a warning. passes a null array */
        test("warning", null);
    }
}

The last line will produce the following warning:

Example.java:26: warning: non-varargs
call of varargs method with inexact
argument type for last parameter;
cast to java.lang.String for a varargs
call
cast to java.lang.String[] for a
non-varargs call and to suppress this
warning

Leave a Comment