0

In my project I have seen many places where constants like INTEGER_ONE, INTEGER_ZERO are used. What is the purpose of using like this? We use constants to change the value in one place that automatically reflects everywhere for particular case, but using constants like INTEGER_ONE is same like using 1, it is common value irrespective of the case they will be using in all places. When we need to change the value of one from the place we obviously need to visit there and change that to another value like INTEGER_N. So why can't we use the numbers directly?

Prasath
  • 57
  • 3
  • 1
    You are on the right track. Don’t use constants like `INTEGER_ONE`. Compare with [this related answer](https://stackoverflow.com/a/41829237/2711488). – Holger Aug 23 '21 at 16:07

2 Answers2

1

If you go through the documentation, you will find that, INTEGER_ONE is stated as:

Reusable Integer constant for one.

And, the actual declaration of INTEGER_ONE is:

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

In Java, values between -128 and 127 are kept in IntegerCache for reuse. So, if you call Integer.valueOf() method with parameter from the specified range, in that case, the same object will be returned all the time. As object creation is expensive, this is one kind of optimization, if you have to use Integer.

But, if you are using primitive types, like int, then there is no need to use INTEGER_ONE, you can directly use 1.

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
0

There is a style rule of not using magic constants. Like 7 - days of week, DAYS_IN_WEEK? However INTEGER_ONE is for any kind of usage for 1 is IMHO even worse.

There is a use case: constant object, to share. BigDecimal.ZERO is such a case. Should INTEGER_ONE not be an int but the wrapper object Integer then you can share the same object, and need not create a plethora of Integer objects with the same value. However Integer.valueOf(n) would also give the same object for values between -128 and 127. In general one should not work with the wrapper classes; Integer here, when using the int values. However collections like List<Integer> use Integers.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138