Srinivasan
Srinivasan

Reputation: 12040

Autoboxing error

FindBugs is telling me I have the following error:

A primitive is boxed, and then immediately unboxed. This probably is due to a manual boxing in a place where an unboxed value is required, thus forcing the compiler to immediately undo the work of the boxing.

Here's the relevant code:

...
String str= "10.0";
Double d = (str != null ? Double.valueOf(str) : new Double(0.0));
...

What does this mean, and how do I fix it?

Upvotes: 4

Views: 1190

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533660

You don't need any auto-boxing or unboxing.

double d = str == null ? 0.0 : Double.parseDouble(str);

The moral is, don't use a Object when you mean to use a primitive.

IMHO Its less confusing to use positive expression instead of negative and double negative boolean expressions.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502006

Looks like a bug in FindBugs to me. If you compile that code and then run javap -c on it, it never calls doubleValue() which is what normally gets used for unboxing.

Admittedly you might want to use a cached Double for zero, rather than allocating one every time this is executed, but other than that it looks reasonable to me...

I suggest you report this to the FindBugs team.

EDIT: Before reporting this to the FindBugs team, I'd update your question with a short but complete program which demonstrates the problem. I took your word for it that the code you showed us was the code FindBugs was complaining about. If that's not the case, all bets are off :)

Upvotes: 5

Lorenzo Manucci
Lorenzo Manucci

Reputation: 880

I tryed your code - FindBugs doesn't display any error. I think that this code significally different from that produces error.

Upvotes: 3

Related Questions