Java sum 2 negative numbers

javanegative-numberplpgsqlsum

I'm trying to convert a function in java to pl/pgsql, and one problem that I found is when I'm trying to sum 2 negative numbers, and a get a positive number, more specifically :

public void sum(){
    int n1 = -1808642602;
    int n2 = -904321301;
    System.out.println(n1 + n2);// result is 1582003393
}

And in pl/pgsql I get an integer out of range error, and if I change the variables type to bigint i get a normal sum of 2 negative numbers, that is -2712963903, instead of 1582003393

How do I do to pl/pgsql get the same result without printing an integer out of range error?

Best Answer

This happens because the Java int underflows and doesn't tell you.

To get the answer you are looking for in pl, you need to use bigint. Then detect the case when the result is less than Java Integer.MIN_INT (-2^31), which is the case where Java will give a positive result. To get what Java would give you, add 2^32.