开发者

How to fix an error with adding integers in Java?

In given e开发者_运维技巧xample:

int a, b, c;
a = 2111000333;
b = 1000222333;
c = a + b;
System.out.println("c= " + c);

will return: c= -1183744630 , why?

How to fix that?


Your integer is overflowing. An integer has a maximum value of Integer.MAX_VALUE (2^31 - 1). If the value becomes bigger, your variable will not have the right value anymore.

A long has a bigger range.

long a, b, c;
a = 2111000333;
b = 1000222333;
c = a + b;
System.out.println("c= " + c);


The MAX_VALUE of a Java long is 9223372036854775807, so Scharrels' solution works for your example.

Here's another solution that can go even higher, should you need it.

BigInteger a = new BigInteger(2111000333);
BigInteger b = new BigInteger(1000222333);
BigIntegerc = a.add(b);
System.out.println("c= " + c);

This approach is bounded only by JVM memory.


long a, b, c;
a = 2111000333;
b = 1000222333;
if (b > LONG.MAX_VALUE - a) {
   // a and b cannot be added.
}


The maximum value of an int in Java is 2,147,483,647. When you want to compute something over this value, you must use the long type.


Java Datatypes

The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜