java类型转换

boolean

  • boolean不可以转换为其他的数据类型

隐式自动类型转换

  • 隐式自动类型转换

    (byte,short,char) < int < long < float < double

byte  ---》    shortintlongfloatdouble
short ---》    intlongfloatdouble
char  ---》    int, longfloatdouble
int   ---》    longfloatdouble
long  ---》    floatdouble
float ---》    double
  • byte能自动转为short,除此,byte,short,char不能自动相互转换
  • 有多种数据类型混合计算的时候,系统首先自动转换为容量最大的那个类型再来继续计算

强制类型转换

  • 容量大的类型在转换为小的类型的时候,必须加上强制转换符,此时可能造成精度降低或者溢出问题
  • 当转换为精度和范围较小的类型时,可能会丢失数据。
int i1 = 128;  
byte b = (byte)i1;  
int i2 = b;  
System.out.println("转换前:" + i1);  
System.out.println("转换后:" + i2); 
/*
    转换前:128
    转换后:-128
/*

byte数据类型范围为-128~127

提升原则

在算术运算和位运算中,数值类型的数据按以下原则进行类型提升
算术运算和位运算byte、short和char型自动转成int型,如:

byte b1=3;
byte b2=5;
byte c=b1+b2;  //错误,运算时b1和b2已转换为int
int d=b1+b2;  //正确
byte b=10;
short s=9;
char c ='c';
short r1=b+s;    //错误
int r2= (b==10)?b:s;  //正确
short r3= (b==10)?b:s;  //正确
byte r4= (b==10)?b:s;  //错误
  • 在其他情况的运算中,运算的对象会自动转换为精度和范围高的类型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值