0

I'm playing with some simple java code and I found something which I cannot explain to myself. I hope some of you can explain it to me.

I have code like this :

public int sum() {
    return Integer.MAX_VALUE + Integer.MAX_VALUE;
}

I wrote a test like this:

@Test
public void testSum() throws Exception {
    Integer num = myclass.sum();
    System.out.println(num);
}

So I'm expecting this to throw some type of exception. But the test prints -2.

Currently my jdk is 1.8.0x60.

Best regards, Petar

M Reza
  • 18,350
  • 14
  • 66
  • 71
Petar Petrov
  • 586
  • 2
  • 10
  • 28
  • 2
    Why did you expect an exception? – Thiyagu Apr 24 '18 at 07:25
  • 5
    take a look at [Integer Overflow](https://en.wikipedia.org/wiki/Integer_overflow) plus [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement). Because that is exactly what's happening. – L.Spillner Apr 24 '18 at 07:27
  • Thanks a lot guys! – Petar Petrov Apr 24 '18 at 07:31
  • Use `return Math.addExact(Integer.MAX_VALUE, Integer.MAX_VALUE);` to get the exception you expected. I agree that the expectation is reasonable, but standard Java math doesn’t give you that. – Ole V.V. Apr 24 '18 at 07:56

0 Answers0