11

I am getting the Findugs error "A boxed value is unboxed and then immediately reboxed".

This is the Code:

Employee emp = new Employee()
Long lmt = 123L;

emp.setLimit(Long.valueOf(lmt)); 

In this, Employee limit field is of type Long. Could you please let me know what is the error?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Srinivasan
  • 11,718
  • 30
  • 64
  • 92
  • 1
    Is there a reason that you're using Long and not long variables and parameters? Since the limit parameter is a Long, why not simply pas `lmt` into the method? Why call `Long.valueOf(lmg)`? – Hovercraft Full Of Eels Aug 22 '12 at 05:19

3 Answers3

22

The problem is that you're converting Long -> long -> Long.

So in the background:

  1. Long.valueOf(lmt) converts Long to long
  2. emp.setLimit(<long>); converts long to Long again

As of Java 5 autoboxing happens => your code should look like this:

Employee emp = new Employee()
Long lmt = 123L;

emp.setLimit(lmt); 

or even:

Employee emp = new Employee()
long lmt = 123L;

emp.setLimit(lmt); 
Peter Butkovic
  • 11,143
  • 10
  • 57
  • 81
4

That happens because Long.valueOf(long) will unbox your lmt from Long to long, just to get a Long again. As you said that limit is a Long, you don't need to use Long.valueOf, just use the var:

emp.setLimit(lmt); 
jpkroehling
  • 13,881
  • 1
  • 37
  • 39
1
emp.setLimit(Long.valueOf(lmt));

Long.valueOf takes a long value, but you pass a Long value -- mandating unboxing. Immediately afterward, however, Long.valueOf re-boxes the value and the expression evaluates to a Long again. FindBugs detects the unnecessary conversion chain Long -> long -> Long.

obataku
  • 29,212
  • 3
  • 44
  • 57
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268