Why does casting Double.NaN to int not throw an exception in Java?

后端 未结 5 1847
执念已碎
执念已碎 2020-12-18 19:20

So I know the IEEE 754 specifies some special floating point values for values that are not real numbers. In Java, casting those values to a primitive int does

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 19:57

    Actually i think during some casting there are bit operations done (probably for perf issues?) so that you can have some unexpected behaviours. See what happens when you use >> and << operators.

    For exemple:

    public static void main(String[] args) {
        short test1 = (short)Integer.MAX_VALUE;
        System.out.println(test1);
        short test2 = (short)Integer.MAX_VALUE-1;
        System.out.println(test2);
        short test3 = (short)Integer.MAX_VALUE-2;
        System.out.println(test3);
        short test4 = (short)Double.MAX_VALUE-3;
        System.out.println(test4);
    }
    

    will output:

    -1
    -2
    -3
    -4
    

提交回复
热议问题