A boxed value is unboxed and then immediately reboxed

Srinivasan picture Srinivasan · Aug 22, 2012 · Viewed 19.2k times · Source

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?

Answer

Peter Butkovic picture Peter Butkovic · Aug 22, 2012

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);