Java入门教程:各类数值型数据间的混合运算


  自动类型转换

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

  转换规则为:

  ① (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型

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

相关内容