3

I am new in java language, here is m not able to understand, why program returning -2 after adding two full range integers.

class Variables {
    public static void main(String[] args) {
        int a = 2147483647;
        int b = 2147483647;
        long c = a + b;
        System.out.println( c );
    }
}

I am expacting 4294967294 value in my variable c, but why it returns -2 please explain me the reason behind this

Rauf Aghayev
  • 300
  • 1
  • 12
MEERA
  • 35
  • 2
  • 1
    You just reach Integer Overflow, the int are first summed as ints, then cast to long, but too late – azro Mar 21 '20 at 18:14
  • Suggestion - learn how integers are represented in memory / binary. Then learn binary addition. Then you'll understand better – OneCricketeer Mar 21 '20 at 18:17

2 Answers2

0

The result of adding two ints is an int, which of course overflows when you add a and b. Only then is it promoted to a long.

You can get the result you expected by casting one of them to long before performing the addition:

long c = ((long) a) + b;
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You reach Integer.MAX_VALUE so you're going to -2147483648, then adding Integer.MAX_VALUE again will result in -2

To get 4294967294, you need to cast one value as long before to do a long sum and not an int one

int a = 2147483647;
System.out.println(a + 1); //-2147483648

int b = 2147483647;
System.out.println(a + b); // -2

long c = a + (long) b; // or ((long) a) + b;
System.out.println(c); //4294967294
azro
  • 53,056
  • 7
  • 34
  • 70