user2150250
user2150250

Reputation: 5157

Passing Null Integer as Parameter

I have a method that takes an Integer baz as an optional parameter via overloading like so ...

public static void myMethod(String fooBar, Integer baz) {

    switch(baz){} // baz gets unboxed, NPE if it was null

    if(baz != null) {
        // Do something
    }
    else {
        // Do something else
    }
}

public static void myMethod(String fooBar) {
    myMethod(fooBar, null);
}

However, it's giving me a warning about the else statement saying it's dead code. But when the method is called without baz, baz should just default to null so this should not be dead code. Any explanation as to what I'm doing wrong here? How would baz always be non-null even though I set it to null in the overloaded method?

EDIT: Deleted actual code so my question is easier to read.

Upvotes: 1

Views: 3426

Answers (2)

Alex Shesterov
Alex Shesterov

Reputation: 27525

You are using switch on the Integer variable. If the Integer is null, switch throws a NullPointerException, which you don't catch.

So it's not possible for the program flow to reach the else condition.

Integers are unboxed if used in switch statement. You have to check for null explicitly, before the switch statement. See also How to use null in switch.


P.S. the minimal code to reproduce the problem is:

public static void myMethod(String fooBar, Integer baz) {

    switch(baz){} // baz gets unboxed, NPE if it was null

    if(baz != null) {
        // Do something
    }
    else {
        // Do something else
    }
}

Upvotes: 4

Neumann
Neumann

Reputation: 761

The only way that Eclipse tells you that your else statement is dead code is that you assign a new Integer to your baz before the if statement, therefore making it impossible to be null.

But since you're only showing a part of your code, that's hard to tell.

EDIT

The switch statement will throw a NullPointerException if tlsVersionMax is null. That's why you else statement is dead code.

Upvotes: 1

Related Questions