Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boxed value unboxed then reboxed

FindBugs is giving me a warning about the following line, where invoiceNumber is an Integer object:

text.append(String.format("%010d-", (invoiceNumber == null) ? 0 : invoiceNumber));

The warning is: "Boxed value is unboxed and then immediately reboxed"

Now I think I understand (un)boxing, but I can't see how you would do the same thing without getting the warning?

I have found that I can get rid of the warning using the following code instead, but this seems more long-winded:

int invNo = (invoiceNumber == null) ? 0 : invoiceNumber;
text.append(String.format("%010d-", invNo));

Can someone show me what is the 'correct' way to do the above?

BTW, I've looked at the related questions and I understand what was going on with them, but this doesn't seem to match any of those.

like image 770
DuncanKinnear Avatar asked Aug 17 '15 04:08

DuncanKinnear


1 Answers

The type of the (invoiceNumber == null) ? 0 : invoiceNumber) expression is int. It requires unboxing of invoiceNumber in the case invoiceNumber is not null.

On the other hand, String.format expects a single String argument followed by Object references, which means your int get immediately boxed to Integer again.

You can try to avoid the original unboxing by using (invoiceNumber == null) ? Integer.valueOf(0) : invoiceNumber), which would make this expression return an Integer.

like image 109
Eran Avatar answered Oct 02 '22 23:10

Eran