-1

I'm new to Java, and trying to translate this code into SQL:

public class hashtest {

    public static void main(String []args) {
        calculateHashCode("asdf","asdf","asdf");
    }

    public static int calculateHashCode(String a, String b, String c) {
        final int prime = 31;
        int result = 1;

        result = prime * result + ((a == null) ? 0 : a.hashCode());
        System.out.println(result);
        result = prime * result + ((b == null) ? 0 : b.hashCode());
        System.out.println(result);
        result = prime * result + ((c == null) ? 0 : c.hashCode());
        System.out.println(result);

        System.out.println(a.hashCode());
        System.out.println(b.hashCode());
        System.out.println(c.hashCode());
        return result;
    }
}

How is it that the value of the result variable flips from positive to negative in the final statement, when all hashcode values are positive?

OUTPUT

enter image description here

I executed this code on (https://www.tutorialspoint.com/compile_java_online.php)

Pops
  • 468
  • 2
  • 15

2 Answers2

1

The multiplication result overflows, continues from the minimum value of int which is -2147483648, giving you a negative result.

S.K.
  • 3,597
  • 2
  • 16
  • 31
0

The multiplication overflows.

If you change the type of result to long (but cast back at the end, of course), you get the output:

Ideone demo

3003475
96111169
2982449683
3003444
3003444
3003444

2982449683 is greater than Integer.MAX_VALUE.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243