Missing Java error on conditional expression?

Using the 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 thing in a method test3()? How does Java evaluate a conditional expression differently in this case? (obviously, a NullPointerExceptionwill grow at runtime). Is this 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!

+3
source share
2 answers

The conditional statement is quite complicated when you mix the type of statements; This is the theme of many Java Puzzlers .

:

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

:

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

, :

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

?: . - .

- Java Puzzlers, 8: Dos Equis:

, . .

JLS

+2

. . ( ). , , :

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

Source: https://habr.com/ru/post/1748781/


All Articles