Radu Dumbrăveanu
Radu Dumbrăveanu

Reputation: 1416

Java: Converting a string to long or integer

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.

Upvotes: 1

Views: 51

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338564

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.

Upvotes: 1

Related Questions