javasonarqubeboxingunboxing

Sonar Bug: Boxed value is unboxed and then again reboxed


I am unable to figure out where the boxed value is unboxed and again reboxed in below sample piece of code. Can some one pls help me in fixing this sonar bug.

List<Float> floatList = new ArrayList<>();
Float hundred = 100F;
Float zero = 0F;
String []stringFloatValues= new String[]{1.2,3.44,5.66};

for(String stringFloat: stringFloatValues){
    Float value = NumberUtils.isParsable(stringFloat)
           ? Float.valueOf(stringFloat) / hundred
           : zero;  // sonar showing issue in this statement
    floatList.add(value);
}

Solution

  • List<Float> floatList = new ArrayList<>();
    float hundred = 100F;
    float zero = 0F;
    String[] stringFloatValues = new String[]{"1.2", "3.44", "5.66"};
    
    for (String stringFloat: stringFloatValues) {
        float value = NumberUtils.isParsable(stringFloat)
               ? Float.parseFloat(stringFloat) / hundred
               : zero;  // sonar showing issue in this statement
        floatList.add(value);
    }
    

    As you calculate, do a division (/), keep everything as primitive type float. Float.valueOf would give a boxed Float, which would need to be unboxed to float, as also hundred. As above - with parseFloatgiving a float -, the resulting float value will be boxed on add.