Java自动类型转换与强制类型转换

在java中低精度的向高精度的转换叫自动类型转换

自动类型转换规则:

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

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

char与(byte、short)    之间不可以转换 但是可以运算  运算时默认为int

(boolean 不参与转换)

高精度的向低精度的转换叫强制类型转换

强制类型转换可能会造成精度损失或者降低

char、byte、short    之间不可以转换 但是可以运算  运算时默认为int

public class Test {
    public static void main(String[] args){
        byte a1=1;
        short a2=1;
        int a3=1;
        char a4=1;

        byte b1=a1+1;    //a1+1是int型,高精度向低精度需要强转 byte b1=(byte)(a1+1);
        byte b2=a2 +1;   //a2+1是int型,高精度向低精度需要强转 byte b2=(byte)(a2+1);
        byte b3=a4 +1;   //a4+1是int型,高精度向低精度需要强转 byte b3=(byte)(a4+1);
        byte b4=a4;      //byte、short、char之间不可以转换 需要强转  byte b4=(byte)a4;
        byte b5=a2;      //byte、short、char之间不可以转换 需要强转  byte b5=(byte)a2;

        short s1=a1+1;   //a1+1是int型,高精度向低精度需要强转 short s1=(short )(a1+1);
        short s2=a2+1;   //a1+1是int型,高精度向低精度需要强转 short s2=(short )(a2+1);
        short s3=a4+1;   //a1+1是int型,高精度向低精度需要强转 short s3=(short )(a4+1);
        short s4=a4;     //byte、short、char之间不可以转换 需要强转  short  s4=(short )a4;
        

        char c1=a1+1;
        char c2=a2+1;
        char c3=a4+1;
        char c4=a1;
        char c5=a2;

        int i1=a1+1;      
        int i2=a2+1;
        int i3=a4+1;
        int i4=a1;
        int i5=a2;

        float f1=1.0; //浮点型默认是double类型 需要强制类型转换或者改成1.0F


    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值