Boxed variable is never null¶
ID: java/non-null-boxed-variableKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - maintainability - readability - typesQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
In Java all of the primitive types have boxed counterparts. The boxed types are objects and can therefore benull, whereas the primitive types can never benull. The names of the primitive and boxed types are similar except that primitive types start with a lower-case letter and boxed types start with an upper-case letter (also, forchar andint the names of the boxed types are slightly longer, namelyCharacter andInteger).
Because the names are so similar and because Java performs automatic boxing and unboxing conversions, they can easily be confused. Furthermore, using a boxed type where a primitive type was intended leads to both readability issues and potentially superfluous allocation of objects.
Recommendation¶
If a variable is never assignednull it should use the primitive type, as this both directly shows the impossibility ofnull and also avoids unnecessary boxing and unboxing conversions.
Example¶
In the example below the variabledone controls the loop exit. It is only set tofalse before the loop entry and set totrue at some point during the loop iteration.
Booleandone=false;while(!done){// ...done=true;// ...}
Each of the assignments todone involves a boxing conversion and the check involves an unboxing conversion. Sincedone is nevernull, these conversions can be completely avoided, and the code made clearer, by using the primitive type instead. Therefore the code should be rewritten in the following way:
booleandone=false;while(!done){// ...done=true;// ...}
References¶
Java Language Specification:Boxing Conversion,Unboxing Conversion.
The Java Tutorials:Autoboxing and Unboxing.