I have a string representing a numerical value, how to decide whether to use Long.valueOf() or is sufficient Integer.valueOf()? The question may be extended to consider the whole range of types: byte, short, int and long.
1 Answer
You asked:
how to decide whether to use Long.valueOf() or is sufficient Integer.valueOf()
Well, you have to know the kind of data expected to be used in your app.
Each numeric integer type has a limit on its range.
- If you know for certain the domain of values valid in your context, choose the most limited type to appropriately represent that fact.
- If you do not know the domain of possible values, then go with the biggest possible range:
long/Long.
A long/Long is a 64-bit value with a range of Long.MIN_VALUE to Long.MAX_VALUE, from 2^63-1 through -2^63. The int/Integer type is a 32-bit value, with a range of a bit more than +/- two billion.
To learn the minimum/maximum range of the various types, look at the Javadoc of their wrapper class for their MIN_VALUE & MAX_VALUE constants. That limit applies to both the respective primitive type and the object type.
4 Comments
short can be useful in expressing the fact that the programmer has determined the domain’s range of values fit within the range of that type.int even they can fit into byte (if there's no requirement to plug byte value somewhere).
Byte.MAX_VALUE,Short.MAX_VALUEorInteger.MAX_VALUE.valueOfif you want the result to be a wrapper. If you want a primitive, always useLong.parseLong/Integer.parseInt/Short.parseShort' /Byte.parseByte.