Reputation: 3060
In given example:
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?
Upvotes: 8
Views: 763
Reputation: 3065
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);
Upvotes: 11
Reputation: 41127
long a, b, c;
a = 2111000333;
b = 1000222333;
if (b > LONG.MAX_VALUE - a) {
// a and b cannot be added.
}
Upvotes: 4
Reputation: 8446
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.
Upvotes: 9
Reputation: 4121
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
Upvotes: 1
Reputation: 7090
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.
Upvotes: 2