Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix an error with adding integers in Java?

Tags:

java

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?

like image 895
Registered User Avatar asked Feb 14 '10 14:02

Registered User


People also ask

What happens if you add an int to a String Java?

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.

What happens if we add int and double 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.


2 Answers

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);
like image 70
Scharrels Avatar answered Oct 08 '22 23:10

Scharrels


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.

like image 42
Drew Wills Avatar answered Oct 08 '22 23:10

Drew Wills