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?
Just add to int or Integer an empty string "" and you'll get your int as a String. It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new String. Object class is a root class in Java.
When one operand is an int and the other is a double, Java creates a new temporary value that is the double version of the int operand. For example, suppose that we are adding dd + ii where ii is an int variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With