When a long integer is cast into a short one, what happened?

前端 未结 4 840
再見小時候
再見小時候 2021-01-18 15:35

I use java to copy one long integer y to a short integer x:

long y = 40002;
short x = (short) y;
System.out.println(\"x now equals \" + x);

4条回答
  •  执念已碎
    2021-01-18 16:07

    Integer overflow happened.

    A short is two signed bytes, which means that Short.MAX_VALUE is 215-1, which is 32,767. "Larger" values logically "wrap around" into the negative range.

    In this case the excess amount is 40,002 - 215 = 7234
    Short.MIN_VALUE is -215 = -32,768
    -32,768 + 7234 = -25,534

    which is the number you're wondering about.

提交回复
热议问题