加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java隐式转换

发布时间:2020-12-14 06:05:16 所属栏目:Java 来源:网络整理
导读:使用以下代码: Float a = 1.2; 有一个错误,因为它将十进制作为double值,double是一个比float更大的数据类型. 现在,它将整数作为默认的int类型.那么,为什么以下代码没有给出任何错误? Byte b = 20; 解决方法 编译器非常聪明,可以确定20的位表示(int值)可以
使用以下代码:
Float a = 1.2;

有一个错误,因为它将十进制作为double值,double是一个比float更大的数据类型.

现在,它将整数作为默认的int类型.那么,为什么以下代码没有给出任何错误?

Byte b = 20;

解决方法

编译器非常聪明,可以确定20的位表示(int值)可以适合一个字节,而不会丢失数据.从 Java Language Specification §5.1.3:

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (07001). This conversion can lose precision,but also lose range,resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits,where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value,this may cause the sign of the resulting value to differ from the sign of the input value.

另见this thread.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读