各类数值型数据间的混合运算

自动类型转换

整型、实型、字符型数据可以混合运算。运算中,不同类型的数据先转化为同一类型,然后进行运算。转换从低级到高级,如下图:

转换规则为:

① (byte或 short) op int→ int

② (byte或 short或 int) op long→ long

③ (byte或 short或 int或 long) op float→ float

④ (byte或 short或 int或 long或 float) op double→ double

⑤ char op int→ int

其中,箭头左边表示参与运算的数据类型,op为运算符(如加、减、乘、除等),右边表示转换成的进行运算的数据类型。

例2.2

public class Promotion{

public static void main( String args[ ] ){

byte b=10;

char c=‘a’;

int i=90;

long l=555L;

float f=3.5f;

double d=1.234;

float f1=f*b;

// float * byte -> float

int i1=c+i;

// char + int -> int

long l1=l+i1;

// long + int ->ling

double d1=f1/i1-d;

// float / int ->float, float - double -> double}

}

强制类型转换

高级数据要转换成低级数据,需用到强制类型转换,如:

int i;

byte b=(byte)i;//把int型变量i强制转换为byte型

这种使用可能会导致溢出或精度的下降,最好不要使用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值