07※、自动类型提升顺序

  ※--自动类型提升顺序

     --小容量的数据类型可以赋值给大容量的数据类型

            基本类型提升的顺序

           byte-->short-->int-->long-->float-->double

int i = 0;
double d = i;
System.out.println(d);//Output result:0.0

           char-->int-->long-->float-->double

16.33F+10//float
int f = 16.33F+10;//compile error:类型不兼容:float类型无法转换为int类型 小转大不通过
float f = 16.33F+10;//Output result:26.33 cause:16.33F是float类型,
//而10是整数类型是java默认的int类型,又因float比int容量大,故java自动提升类型。
16.33F+10.99//double
float f = 16.33F+10.99;//compile error:类型不兼容:double类型无法转换为float类型 小转大不通过
double d = 16.33F+10.99;Output result:27.31 cause:16.33F是float类型,
//而10.99是整数类型是java默认的double类型,又因double比float容量大,故java自动提升类型。

    --强制类型转换

   --大容量的数据类型赋值给小容量的数据类型会有类型兼容问题,不能直接赋值,除非通过强制类型转换

            语法格式:

            类型1  变量a =  (类型1) 变量b

            类型1  变量a =  (类型1) (表达式)

    /**
      *
      * @Author Lantzrung
      * @Date 2022年7月16日下午4:44:42
      *  
      **/
    byte item1 = 2;//102
    byte item2 = 3;//103
    byte item3 = item1+item2;
    //编译错误:不兼容的类型: 从int转换到byte可能会有损失 [原因:两数相加的和是大于127]
    solution:byte item4 = (byte)(item1+item3)
    System.out.println("item4="+item4);//结果:-51    
    //205-128-->77-->-127+77-->-50 因为0不用算故此 要向前移动一位 -50-1-->-51
    //(int强转byte类型容量不足,溢出,故从byte类型的最小值取值开始)
    
    byte b = 182;//编译错误: 不兼容的类型: 从int转换到byte可能会有损失
 
    solution:byte b = (byte)182;结果:-74
    //(int强转byte类型容量不足,溢出,故从byte类型的最小值取值开始)   
    byte b1 = 2;//程序能输出2  
        
    short s = 45182;//编译错误:不兼容的类型:从int转换到short可能会有损失
    solution: short s1 = (short)45182;//结果:-20354 和上述同理        
    int i = 21000000000;//编译错误:过大的整数:21000000000 210亿 int最大的整数值为21亿左右
    long l = 21000000000;//错误:过大的整数:21000000000
    solution:long l1 = 21000000000L;//在过大数值中加上L的字母就可以把int类型数组提升为long类 
    //型数组
    System.out.println(l1);//210000000000
    
    int item1 = 67;
    byte item2 = item1;//编译error:不兼容的类型:从int转换到byte可能会有损失    
    solution:byte item2 = (byte)item1;//67 强转
    short item3 = item1;//编译error:不兼容的类型:从int转换到short可能会有损失
    solution:short item3 = (short)item1;//67 强转 

        

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Lantzruk

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

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

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

打赏作者

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

抵扣说明:

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

余额充值