-1

Lets consider below lines of code.

1- int ExA = Integer.parseInt("123");
2- int ExB = Integer.parseInt("2147483660");

if we execute line 1 than variable ExA will be successfully populated by 123

but if we execute line 2 than we will "NumberFormatException" because in line 2 number provided to the 'parseInt' function is beyond int range.

I am looking for a solution where I can get overflowed int value if we have a number in string format whose value is beyond int range. Please help me figuring out.

Zhubei Federer
  • 1,274
  • 2
  • 10
  • 27
Farhan
  • 105
  • 1
  • 10

2 Answers2

3

You can use BigInteger instead.

BigInteger ExB = new BigInteger("2147483660");

Regarding JDK docs,

BigInteger must support values in the range -2^Integer.MAX_VALUE (exclusive) to +2^Integer.MAX_VALUE (exclusive) and may support values outside of that range. The range of probable prime values is limited and may be less than the full supported positive range of BigInteger. The range must be at least 1 to 2^500000000

Tran Ho
  • 1,442
  • 9
  • 15
  • its not just about BigInteger or long value consider I have string like this - "342342342342342342423442121333123" which is beyond any data type range. – Farhan Jun 04 '19 at 02:01
  • then it's better to store it as a string and make some algorithm to add, subtract, multiply, divide, etc. but it will be much more complicated. – Tran Ho Jun 04 '19 at 02:05
  • @Farhan why do you think that's beyond the type range of BigInteger? And why do you think it's better to write your own code than to use BigInteger? – Louis Wasserman Jun 04 '19 at 02:16
  • 1
    @Farhan `"342342342342342342423442121333123"` is *not* beyond the range of `BigInteger`. – user207421 Jun 04 '19 at 04:08
0

BigInteger is sometimes messy to implement. You could have a long, and just do Long.parseLong("2147483660"), if it doesn't exceed 2^64.

Raymo111
  • 514
  • 8
  • 24