javaapache-commons-lang

Benefits of using NumberUtils.INTEGER_ONE and other such utilities


In java for a comparison in an if statement, I wrote

if (x == 1)

and got a comment in code review to use NumberUtils.INTEGER_ONE instead of 1. I was wondering what benefit does it actually add to the code.


Solution

  • NumberUtils.INTEGER_ONE comes probably from commons-lang.

    In commons-lang, it is defined as :

    public static final Integer INTEGER_ONE = new Integer(1);
    

    In commons-lang3, it is defined as :

    public static final Integer INTEGER_ONE = Integer.valueOf(1);
    

    The first version doesn't use the internal integer cache (as didn't exist yet) while the second version takes advantage of it.

    Now, whatever the version you are using, it doesn't really matter for your question as you compare integer values and you don't assign or create integer value (case where the cache could make more sense).


    Suppose you are using it in this way :

    if (x == NumberUtils.INTEGER_ONE)