javacastinginteger-overflow

Casting an expression to long doesn't seem to have an effect


I really struggle to solve this error and I can't find anything on the internet. If I do:

long test = (long) (2147483647 + 1);

it sets test to an int even though I used long. Why?

I tried it using max int value but it still doesn't work.

long test = (long) (Integer.MAX_VALUE + 1);

Solution

  • cast then add

    long test = (long) (2147483647) + 1;
    System.out.println(test);
    

    2147483648

    Otherwise you are adding two ints then casting