数据转换

来源:互联网 发布:网吧维护公司网站源码 编辑:程序博客网 时间:2024/05/16 11:09
  1. 基本数据类型转换
    boolean类型不可以转换为其他的数据类型
    整形,字符型,浮点型的数据在混合运算中相互转换,转换时遵循以下原则:
    容量小的类型自动转换为容量大的数据类型;数据类型按容量大小排序为:
    byte,short,char->int->long->float->double
    byte,short,char之间不会互相转换,他们三者在计算时首先会转换为int类型
    容量大的数据类型转换为容量小的数据类型时,要加上强制转换符.但可能造成精度降低或溢出;使用时要格外注意
    有多种类型的数据混合运算时,系统首先自动的将所有数据转换成容量最大的那一种数据类型,然后再进行计算
    实数常量默认为double
    整数常量默认为int

 

  1. public class TestConvert {
  2.     public static void main(String arg[]) {
  3.         int i1 = 123; 
  4.         int i2 = 456;
  5.         double d1 = (i1+i2)*1.2;//系统将转换为double型运算
  6.         float f1 = (float)((i1+i2)*1.2);//需要加强制转换符
  7.         byte b1 = 67; 
  8.         byte b2 = 89;
  9.         byte b3 = (byte)(b1+b2);//系统将转换为int型运算,需
  10.                                 //要强制转换符
  11.         System.out.println(b3);
  12.         double d2 = 1e200;
  13.         float f2 = (float)d2;//会产生溢出
  14.         System.out.println(f2);
  15.         float f3 = 1.23f;//必须加f
  16.         long l1 = 123;
  17.         long l2 = 30000000000L;//必须加l
  18.         float f = l1+l2+f3;//系统将转换为float型计算
  19.         long l = (long)f;//强制转换会舍去小数部分(不是四舍五入)
  20.     }
  21. }
    1. public class Test { 
    2. public static void main(String args[])
    3. {
    4.     int i = 1, j;
    5.     float f1 = 0.1;//出错0.1是double
    6.     float f2 = 123;//
    7.     long l1 = 12345678;
    8.     long l2 = 8888888888;//有问题,超出
    9.     double d1 = 2e20;//没问题
    10.     double d2 = 124;//
    11.     byte b1 = 1;
    12.     byte b2 = 2;
    13.     byte b3 = 129;//有问题
    14.     j = j+10;//j没值
    15.     i = i/10;//没问题,i=0
    16.     i = i*0.1;//有问题0.1是double
    17.     char c1 = 'a';
    18.     char c2 = 125;
    19.     byte b = b1-b2;//有问题b1,b2先转换为int
    20.     char c = c1+c2-1;//有问题
    21.     float f3 = f1 + f2;
    22.     float f4 = f1 + f2*0.1;//有问题0.1是double
    23.     double d = d1*i+j;
    24.     float f = (float)(d1*5+d2);
    25. }
原创粉丝点击