Why does this chained conditional operator throw NPE? - java

Boolean isTrue = condition1 ? true : (
id == null ? null : condition2);
When condition1 returns true, the code runs fine(makes sense), but when condition1 is false, the code fails with a null pointer exception.
Try it yourself - https://www.ideone.com/epj9Jd
This is slightly confusing and doesn't make sense. An explanation for this would be appreciated.

Boolean isTrue = condition1 ? true : (
id == null ? null /* <- HERE*/ : condition2);
OK, so this is a bit gnarly. The problem is due to the null value introduced at the point labeled HERE being unboxed.
Why?
Because the type of condition1 ? true : ... is the type of the 2nd operand; i.e. boolean. Therefore the subexpression id == null ? null : condition2 which is Boolean has to be unboxed to a boolean.
But unboxing a null gives you a NPE.
Interesting. I would have expected better type inference here.
Unfortunately, the rules for typing of conditional expressions involving boxed types were solidified in Java 5 when autoboxing / unboxing were added to the language. That was 15 (?) years before Java got significant support for type inferencing.
Once the rules were solidified, they couldn't be changed ... without breaking backwards compatibility.
(But actually this is not a type inference problem. The typing is fine. The real problem here is that there are two possible semantics for this, one that involves unboxing null and the other that doesn't. The JLS rules for typing conditionals mean that the first one is used in this case.)

Related

Why is Java evaluating the wrong side of ternary operation?

I might miss some simple explanation, but the following line throws a NullPointerException:
Long sum = true
?
fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice())
:
(long) fiscalDocument.getReceipt().getAmount();
While
Long sum = true
?
fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice())
:
null
does not. I would also like to mention that
fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice())
does not throw an exception on its own, while
(long) fiscalDocument.getReceipt().getAmount()
does.
Is the second side evaluated? Or am I butchering something?
EDIT
Some additional info, asked in the comments:
fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice()) returns null.
The return type of fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice()) is Long.
The return type of fiscalDocument.getReceipt().getAmount() is Integer.
If I emit the explicit (long) conversion, the behavior is the same.
Edit 2
A minimal reproducible example: Long val =true ? (Long) null: Integer.valueOf(1);. This was partially suggested by the answer of MC Emperor and partially suggested by comments. Of course, this example already somewhat answers the question, since the second expression does not need to throw an exception, as it turns out.
If foo has type Long and bar has type long, then true ? foo : bar has type long, and is equivalent to true ? foo.longValue() : bar. As the Java Language Specification puts it:
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
(In your case, T is long, and "the result of applying boxing conversion (§5.1.7) to T" is Long.)
The fact that you try to put the result in a Long variable doesn't change that fact; it just gives you the equivalent of Long.valueOf(true ? foo.longValue() : bar), with unboxing followed by boxing.
In your case, foo == null, so the unboxing throws a NullPointerException, so the boxing never happens.
Well, Java only evaluates the left expression, as the condition is true.
You said that fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice()) in itself does not throw an NullPointerException.
The only thing I can think of, is that fiscalDocumentUtil.getFullValue(fiscalDocument.getInvoice()) returns null. Reproducible with:
Long sum = true ? null : (long) 23L;
Because one of the operands is a primitive, the other one is subject to boxing conversion, in this case, unboxed to long.

Confused about ? -1 : true [duplicate]

I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

The meaning of ? in a java line [duplicate]

I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

While("abc"); causes an error in java and it does not cause any error in c . Why?

I tried the below code in both java and c++ , but it throwed an error in java while it does not throw an error in c++. Why is it so ?
while("abc"){ }
I do know it purely depends on the property of languages. But I would like to know why java set a condition that only boolean values should be allowed in loops ?
I believe you are talking about compiler error and not run-time
in case of java
while ( expression ) {
// expression must evaluate to boolean value true or false
// as far as I knwo "abc" is neither true or false when it comes to java hence error
}
in C
while ( expression ) {
// expression can be anything which finally gives a value of either 0 or a number
// "abc" in this case will evaluate to an address which is positive integer hence no error
}
It is because of the same reason that while(1) is allowed in C but not in Java. Both of the languages evaluate expressions differently.
In case of C, there was originally no boolean type (it was introduced in C99), and any integer that is 0 was decided to be 'false', otherwise to be considered 'true'. In expression:
while("abc")
It resolves to the address which is positive integer so it works.
In case of Java, expressions must evaluate to true or false value. String "abc" does not evaluate to a boolean value so an error is observed.
Because in java The while statement evaluates expression, which must return a boolean value.You can read about it here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
C allows you to type anything you want in a condition of while loop.
If you dissasemble C while( something ), you will see, that the value in the parentheses is loaded in the eax register (in your case, value in the parentheses is the address of "abc"), then eax checks for zero and, if it is zero, loop ends. Like this:
mov eax, <"abc" offset>
test eax, eax
je <"after loop" offset>
jmp <loop offset>
P.S.:Because "abc" offset is a non-zero value, your loop will never end.
Note that C is the oddball in this case, not Java. Most of C's contemporaries (Fortran, Pascal, old-school BASIC, etc.) behave like Java, where the condition must be a Boolean value (or a Boolean-valued expression). C didn't acquire a true Boolean datatype until the 1999 revision, long after a whole generation of C programmers (myself included) grew accustomed to writing code without it.
In C, any non-zero integral value is considered true in a Boolean context. It's a common idiom to check that a pointer value isn't NULL as follows:
FILE *in = fopen( filename, "r" );
if ( in )
{
// in is not NULL, fopen was successful
}
As long as the pointer value in is not NULL, the condition evaluates to true. The risk with this approach is that non-NULL pointer values aren't necessarily valid pointer values. It will be in this case (fopen will return either a valid pointer value or NULL), but code like the following:
void foo ( void )
{
int *p;
...
if ( p ) { ... }
...
}
is risky; if p is never initialized or assigned to, then it will contain an indeterminate value which will most likely be neither a valid pointer nor NULL.
In most other languages, the same condition would be written as the equivalent of
if ( in != NULL )
which is a Boolean-valued expression that can only yield the values true and false.
Since "abc" evaluates to a non-zero pointer value, it can be used in a similar context (although it's not very useful, since the address will never change).

Java ternary operator function overloading [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java conditional operator ?: result type
NullPointerException through auto-boxing-behavior of Java ternary operator
Say I have two functions:
f(MyObject o) { ... }
f(int i) { ... }
And I call them like this:
f(someCondition ? 10 : null);
This compiles, but when I run it I get a null pointer exception (sorry I'm not sure on which condition). Some my questions are:
Why does it even compile? What is the type of foo ? 10 : null?
It clearly doesn't call the "correct" functions because that wouldn't cause an NPE. So which function is it calling? Does it do f((MyObject)10); or f((int)null)?
First of all, the problem doesn't have anything to do with the fact that you have overloaded versions of f. If you only have the version of f that takes an int, you get the same problem.
The thing is that both possible results of the ternary expression (before and after the :) must have the same type, because the whole expression condition ? expr1 : expr2 must have a single type. You can't have this expression evaluate to one type of condition is true, and another type if it is false.
So, the Java compiler is going to see if it can convert expr1 and expr2 to a single type. Note that int cannot be null (because it's a primitive type). However, 10 can be converted to Integer via autoboxing, and an Integer can also be null. So the type of the whole ternary expression is determined to be of type Integer. The result is either an Integer that contains the value 10 or an Integer that is null.
Step two is that you pass this Integer to f. Because f takes an int, it is auto-unboxed.
If you auto-unbox an Integer that is null, you get a NullPointerException - that's what happens here.
The type is Integer - an auto boxing is done to the 10.
f(int) is called, because it is the only accepted cast from Integer available (assuming no other overloads)
When you try to cast a null to an int - you get your NPE.
2. f(Object) is called since Integer is an Object. This is called reference type widening
(sorry for the initial mistake, read it as f(Object))

Categories