-4

I am a newbee in Java and stumbled upon a such question: What happens if a variable is Integer.MAX_VALUE?

System.out.println(2 * a);
System.out.println(4 * a);

Both give -2 and -4 results accordingly. Can someone explain me why this is it? I read about primitive int type overloading but still don't understand why I got these results?

Mario Codes
  • 689
  • 8
  • 15
  • 1
    There is a ton of information online about this. Here is one example; https://www.baeldung.com/java-overflow-underflow – Jason Aug 26 '20 at 16:51
  • I understood the integer-wraparound concept in case of adding or subtracting 1 from Integer.MAX_VALUE. But why when I multiply it gives an opposite integer number? Is it default behavior for the case when MAX_VALUE multiplied in JAVA? – brain2life Aug 26 '20 at 17:02

1 Answers1

1

In binary, Integer.MAX_VALUE is

Integer.MAX_VALUE = 0111 1111 1111 1111 1111 1111 1111 1111

If you multiply this number by 2, the result is the same as shifting all bits left by 1 and adding a 0 on the right:

2*Integer.MAX_VALUE = 1111 1111 1111 1111 1111 1111 1111 1110

What happens if you now add 2, or 10 in binary? Thanks to overflow, all bits cancel out and you get

2 + 2*Integer.MAX_VALUE = 0

or in other words

2*Integer.MAX_VALUE = -2

There is another way to see this. In binary, -1 is all ones:

-1 = 1111 1111 1111 1111 1111 1111 1111 1111.

So when you multiply -1 by 2 you get:

2*(-1) = 1111 1111 1111 1111 1111 1111 1111 1110

Again you see 2*Integer.MAX_VALUE = -2

Joni
  • 108,737
  • 14
  • 143
  • 193