Dhananjay
Dhananjay

Reputation: 69

FindBugs - Boxed value is unboxed and then immediately reboxed

Getting Boxed value is unboxed and then immediately reboxed error in following code snippet. Please help me understand where is the issue?

     public Integer convert(String str) {
        String result = Optional.ofNullable(str)
            .filter(sStr -> sStr.length() != 0)
            .map(sStr -> sStr.substring(0, sStr.length() - 1))
            .orElse(StringUtils.EMPTY);
        return result.isEmpty() ? 1 : Integer.valueOf(result);
     }

FindBugs and SpotBugs show the warning: Boxed value is unboxed and then immediately reboxed (BX_UNBOXING_IMMEDIATELY_REBOXED) for the last statement of the method when rules with rank >= 18 are enabled.(not enabled by default at least in SpotBugs)

Upvotes: 0

Views: 2003

Answers (1)

rmunge
rmunge

Reputation: 4248

The ternary operator (?:) is a bit tricky in combination with boxing/unboxing. If str is not empty, your last line of code will:

  1. Call the method Integer.valueOf(String)

  2. This method calls Integer.valueOf(parseInt(s, 10)); that converts an int value to an Integer object (first boxing)

  3. Since you use an int value in the first part of the ternary operator, the returned Integer object is converted to an int value (unboxing)

  4. Finally the int value is converted to an Integer object before the return (second boxing)

To sum it up: Instead of one Integer object the code creates two Integer objects. This is not really a problem in most scenarios. Therefore the corresponding FindBug rule has only a rank of 18 and is by default disabled. The unecessary creation of the object could get a problem when your code is executed frequently in a high load scenario where the creation of millions of short-lived objects within a short period of time has negative impact on the garbage collector.

You can avoid this warning by either replacing 1 with (Integer)1 or Integer.valueOf(1). Both will produce the same byte code and avoid the unecessary creation of the second Integer object.

Upvotes: 4

Related Questions