Registered User
Registered User

Reputation: 3060

How to fix an error with adding integers in 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?

Upvotes: 8

Views: 763

Answers (5)

Scharrels
Scharrels

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

fastcodejava
fastcodejava

Reputation: 41127

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

Upvotes: 4

Drew Wills
Drew Wills

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

Tommy
Tommy

Reputation: 4121

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

Upvotes: 1

Desintegr
Desintegr

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

Related Questions