《JAVA编程思想》学习备忘(第93页:Operators--3)

  续《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
(略)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值