基本类型转换,各种类型转换的优先级顺序

类型转换

由于Java是强类型语言,所以要进行有些有些运算的时候,需要用到类型转换。

类型转换的优先级顺序

  • byte,short,char

  • int

  • long

  • float

  • double

注意以上排序是按照有低到高排序

运算中,不同类型的数据想要比较,必须先转化为同一类型的,然后才能进行比较。

注意

  • 不能对布尔类型转换

  • 不能把对象类型转换为不相干的类型

  • 把高容量转换为低容量的时候,强制转换,低容量转换成高容量时不需要强制类型转换。(如下图 )

    • 运行结果

  • 转换的时候可能出现内存溢出,或者精度的问题

代码如下

 public class Demo05 {
     public static void main(String[] args) {
         int i =128;
         byte b = (byte)i;
         System.out.println(i);
         System.out.println(b);//内存溢出
         //强制类型转换     由高到低需要转换
         //自动类型转换     由低到高自动转换
         System.out.println((int)23.4);
         System.out.println((int)-45.89f);//精度丢失
         char c = 'a';
         int d = c + 1;
         System.out.println(d);
         System.out.println((char)d);
         //操作数比较大的时候,注意溢出问题
         int money = 1000000000;
         int years = 20;
         int total = money*years;
         System.out.println(total);//溢出
         long total2 = money*years;
         System.out.println(total2);
         long total3 =money*((long)years);//一定要先进行强制类型转换,再进行计算
         System.out.println(total3);
     }
 }
 ​
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LNORA

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

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

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

打赏作者

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

抵扣说明:

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

余额充值