Java隐式转换

使用以下代码
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.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...