views:

85

answers:

2

With methods test1() and test2(), I get a Type Mismatch Error: Cannot convert from null to int, which is correct; but why am I not getting the same in method test3()? How does Java evaluate the conditional expression differently in that case? (obviously, a NullPointerException will rise at runtime). Is it a missing error?

public class Test {

    public int test1(int param) {
        return null;
    }

    public int test2(int param) {
        if (param > 0)
            return param;
        return null;
    }

    public int test3(int param) {
        return (param > 0 ? param : null);
    }

}

Thanks in advance!

+2  A: 

See the answer to this question. Basically the compiler will attempt to auto-unbox the null value (and throw a null pointer exception). I assume this is the syntax that you had trouble with:

public int test3(int param) { 
    return (param > 0 ? param : null); 
} 
Yishai
Yes, that's the right syntax. It was my mistake when I was writing the question. And thanks for the link, very interesting!
Federico Cristina
+2  A: 

The conditional operator is quite tricky when you mix the type of the operators; it's the subject of many Java Puzzlers.

Here's a classic example:

System.out.println(true ? Integer.valueOf(1) : Double.valueOf(2));
// prints "1.0"!!!

And here's another:

System.out.println(true ? '*' : 0);     // prints "*"
int zero = 0;
System.out.println(true ? '*' : zero);  // prints "42"

And, as you've just discovered:

System.out.println(true  ? 1 : null);   // prints "1"
System.out.println(false ? 1 : null);   // prints "null"

Understanding all the intricacies of the the conditional operator ?: can be quite hard. The best advice to give is to simply not mix types in the second and third operands.

The following quote is an excerpt from the lesson of Java Puzzlers, Puzzle 8: Dos Equis:

In summary, it is generally best to use the same type for the second and third operands in conditional expressions. Otherwise, you and the readers of your program must have a thorough understanding of the complex specification for the behavior of these expressions.

JLS references

polygenelubricants
Great explanation! Looks like it's safer to use if statements instead. Thanks for your time!
Federico Cristina