Autoboxing and Nullpointer [message #524083] |
Tue, 30 March 2010 11:44  |
Eclipse User |
|
|
|
Hello,
could someone please explain me, why the following snippet produces a NullPointerException:
public class Main {
public static void main(String[] args) {
System.out.println(getDouble());
Double d1 = true ? getDouble() : new Double(0);
System.out.println(d1);
Double d2 = true ? getDouble() : 0;
System.out.println(d2);
}
public static Double getDouble() {
return null;
}
}
The output is:
null
null
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:9)
Apparently it has to do with autoboxing, but is this the right behaviour?
I'm using Eclipse Galileo for RCP/Plug-in Developers, Build id: 20090920-1017
Thank you in advance,
Rudi
|
|
|
|
|
Re: Autoboxing and Nullpointer [message #524320 is a reply to message #524083] |
Wed, 31 March 2010 05:26  |
Eclipse User |
|
|
|
On 3/30/2010 9:44 AM, Rudi wrote:
> Hello,
>
> could someone please explain me, why the following snippet produces a
> NullPointerException:
>
> public class Main {
>
> public static void main(String[] args) {
>
> System.out.println(getDouble());
>
> Double d1 = true ? getDouble() : new Double(0);
> System.out.println(d1);
>
> Double d2 = true ? getDouble() : 0;
> System.out.println(d2);
> }
>
> public static Double getDouble() {
>
> return null;
> }
> }
>
> The output is:
>
> null
> null
> Exception in thread "main" java.lang.NullPointerException
> at Main.main(Main.java:9)
>
>
> Apparently it has to do with autoboxing, but is this the right behaviour?
> I'm using Eclipse Galileo for RCP/Plug-in Developers, Build id:
> 20090920-1017
>
>
> Thank you in advance,
> Rudi
While the ternary operator in Java has understandable problems for which
I lodge no particular complaint (despite being an old C guy who uses
this construct copiously), in this case, it's the null returned from
getDouble() that leads to the exception and not the ternary operation's
innate grumpiness, no?
Russ
|
|
|
Powered by
FUDForum. Page generated in 0.13212 seconds