Re: Ternary op + autoboxing + null value = NPE?
Re: Ternary op + autoboxing + null value = NPE?
- Subject: Re: Ternary op + autoboxing + null value = NPE?
- From: "Sobanski, Jedrzej" <email@hidden>
- Date: Tue, 20 Oct 2009 15:19:41 +0200
- Acceptlanguage: en-US
- Thread-topic: Ternary op + autoboxing + null value = NPE?
Hi all,
That's interesting issue. Compiler when running into ..?..:..
expression first determines its common type, then applies autoboxing
and then optimizes the expression. Let's consider two types:
(1) <condition> ? Double : double
(2) <condition> ? Double : Double
I think compiler determines common type for (1) as 'double' (perhaps
for performance reasons?), while for (2) it's 'Double'
Then it applies autoboxing where needed. If (1) and (2) are being
assigned to Double, then (2) doesn't need to be boxed, while both
arguments in (1) are wrapped with Double.valueOf(..).
At the end it optimizes the whole expression. As what's in front of
'if' is always true, it leaves out only the middle argument.
This way the following code:
Double v1 = null;
Double v2 = true ? v1 : 0d;
gets compiled and then decompiled to ridiculous form:
Double v1 = null;
Double v2 = Double.valueOf(v1.doubleValue());
Regards,
Jedrzej
On Oct 19, 2009, at 5:31 PM, Ramsey Gurley wrote:
> Hi all,
>
> I've just discovered that while
>
> Double test = true?null:0d; //result: test is null
>
> works without error, the following
>
> Double test2 = true?(new Object(){public Double testMethod(){return
> null;}}.testMethod()):0d; //<-Throws NPE
>
> Throws a NullPointerException. :-/ Ok, that sucks, so what about
> this?
>
> Double test3 = new Object(){public Double testMethod2(){return
> null;}}.testMethod2(); // result: test3 is null
> Double test4 = true?test3:0d; //<-Throws NPE
>
> Also throws a NullPointerException. I suspect this has something to
> do with the autoboxing, because
>
> Object test5 = true?new Object(){public Object testMethod3(){return
> null;}}.testMethod3():0d;
>
> Works fine. I'm running OS X 10.5 and java 1.5 here at work. Is this
> a known issue? Or is this somehow expected behavior?
>
> Ramsey
>
>
> _______________________________________________
> Do not post admin requests to the list. They will be ignored.
> Webobjects-dev mailing list (email@hidden)
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Webobjects-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden