Java基础05_类型转换

  • 由于Java是强类型语言,所以在进行一些运算的时候,需要用到类型转换;
  • 不能对 boolean 进行转换;
  • 转换的时候可能存在内存溢出的问题,或者是精度的问题;
public class Demo04 {
    public static void main(String[] args) {
        double f = -10.71;
        int e = (int)f;
        System.out.println(e);//-10
    }
}
	低---------------------------------------------------------->高
	  byte,short,char  —>  int  —>  long  —>  float   —>  double

运算中,不同类型的数据先转换为一类,再进行运算;

  • 强制转换:高—>低
  • 自动转换:低—>高
public class Demo04 {
    public static void main(String[] args) {
        byte b = 127;
        int a = b;
        System.out.println(a);//自动转换

        int c = 100;
        byte d = (byte)c;
        System.out.println(d);//强制转换
    }
}

操作比较大 的数字的时候,注意内存溢出的问题;

  • JDK7新特性,数字之间可以用下划线隔开,这样便于观察;
public class Demo05 {
    public static void main(String[] args) {
        int money = 10_0000_0000;
        int years = 20;
        int total = money * years;
        System.out.println(total);//-1474836480 内存溢出

        long total2 = money * years;
        System.out.println(total2);//-1474836480 还是内存溢出 因为money和years默认都是int类型的变量 他们的计算值money * years也是int int再次转换为long也是错的

        //正确写法
        long total3 = money *(long)years;
        System.out.println(total3);//20000000000
        long money3 = 10_0000_0000L;
        long years3 = 20L;
        long total4 = money3 * years3;
        System.out.println(total4);//20000000000
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清纯献给了作业

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值