设为首页 加入收藏

TOP

Java入门教程:各类数值型数据间的混合运算
2014-11-24 02:43:27 来源: 作者: 【 】 浏览:1
Tags: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型


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java入门教程:布尔型数据 下一篇Java值传递和引用传递

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: