续《JAVA编程思想》学习备忘(第93页:Operators--2)
Common pitfalls when using operators
运算符使用中的“陷井”
一个Java中的错误例子:
while(x=y){
//...
}
当x和y是boolean类型是,x=y是一个合法的表达式,能通过编译,如果y的值为true,则此例会产生一个死循环。
Casting operators
强转运算符
看下边的例子:
public class Casting{
public static void main(String[] args){
int i = 200;
long lng = (long)i;
lng = i; //"Widening," so cast not really required
long lng2 = (long)200;
lng2 = 200;
// A "narrowing conversion"
i = (int)lng2; //Cast required
}
}
Java allows you to cast any primitive type to any other primitive type,except for boolean.
除boolean类型外,Java允许你将任意一种原始数据类型强转成别的原始数据类型。
Truncation and rounding
当进行数据类型大转小(narrowing conversions)时,你必须注意截断和舍入。
举例:
import static staticPrint.Print.print;
public class CastingNumbers{
public static void main(String[] args){
double above = 0.7,below = 0.4;
float fablove 0.7f,fbelow = 0.4f;
print("(int)above: " + (int)above);
print("(int)below: " + (int)below);
print("(int)fabove: " + (int)fabove);
print("(int)fbelow: " + (int)fbelow);
}
}
以上输出均为0
上例可以看出,当从float或者double转整形值时(“大转小”),总是截断数字。
再来看看舍入的例子:
import static staticPrint.Print.print;
public class RoundingNumbers{
public static void main(String[] args){
double above = 0.7,below = 0.4;
float fablove 0.7f,fbelow = 0.4f;
print("Math.round(above): " + Math.round(above));
print("Math.round(below): " + Math.round(below));
print("Math.round(fabove): " + Math.round(fabove));
print("Math.round(fbelow): " + Math.round(fbelow));
}
}
以上输出:
Math.round(above):1
Math.round(below):0
Math.round(fabove):1
Math.round(fbelow):0
Promotion
提升(小转大)
小转大后,再大转小,则必须截断,这将丢失精度。
通常情况,表达式中的最大的数据类型,决定了结果类型,如果一个float与一个double相乘,结果必为double;如果一个int与一个long相加,则结果必为long 。
Java has no "sizeof"
Java does not need a sizeof() operator for this purpose,because all the data types are the same size on all machines.
A compendium of operators
(略)
本文探讨了Java中运算符的常见陷阱,并详细讲解了类型转换的规则与注意事项,包括窄化转换时的截断与舍入问题。
339

被折叠的 条评论
为什么被折叠?



