Java中的基本数据类型类型提升现象

本文转载自http://blog.csdn.net/wang740209668/article/details/57416778

一般来说,在运算的时候,要求参与运算的数据的类型须一致,这就好比我们能用1+1进行运算,而不能用1+a进行运算,而在java中更为严格,同为数值的数字有byte short int long 四种不同的类型,它们在运算的时候也要求类型一致,如果不一致,就涉及到我们今天要说的类型转换。

默认转换:

[java] view plain copy
  1. class TypeConvert  
  2. {  
  3.     public static void main(String[] args){  
  4.        // 类型一致 直接运算   
  5.       int a = 1;  
  6.       int b = 2;  
  7.       System.out.println(a+b);  
  8.       // 类型不一致 默认转换 按道理讲 c+d=3 是没有超出byte 范围的  
  9.       // 但当我们用byte接收的时候,编译报错 可能损失精度。说明此时  
  10.       // e 不是byte类型,而运算的过程中byte c默认转换为 int c  
  11.       // 此时 结果 e 也是int类型了 ,我们需要用 int 接收  
  12.       byte c = 1;  
  13.       int d = 2;  
  14.       //byte e = c+d; 是int不是byte  
  15.       int e = c+d;  
  16.       System.out.println(e);  
  17.       // byte 和 byte 结果也是 int  
  18.       byte x = 1;  
  19.       byte y = 2;  
  20.       //byte z = x+y;  
  21.       int z = x+y;  
  22.       System.out.println(z);  
  23.     }  
  24. }  


默认转换顺序(从小到大,向上转型):

byte short char ->int->long->float->double    

byte short char 运算时转换为int ,运算中有long类型则结果是long类型,有double类型,结果是double类型。

byte short char 相互之间不转换,它们运算时先转换为int类型。

/*

    这一段为转载后插入

    short s = 1;
    s+=1;//不报错
    //s = s+1;//报错 int不能复制给short

    就是这个原因。+=不会提升数据类型 先+再赋值会

    基本数据类型的字节大小如下:

  boolean  8bit/1byte
      byte      8bit/1byte
      char      16bit/2byte
      short     16bit/2byte
  float      32bit/4byte
      int        32bit/4byte
      long      64bit/8byte
      double  64bit/8byte

*/

强制转换(从大到小,向下转型):

格式   目标数据类型  变量 = (目标数据类型) 数据;

[java] view plain copy
  1. class TypeConvert  
  2. {  
  3.     public static void main(String[] args){  
  4.       byte a = 1;  
  5.       byte b = 2;  
  6.       // 强制类型转换  
  7.       byte c = (byte)(a+b);  
  8.       System.out.println(c);  
  9.     }  

发布了106 篇原创文章 · 获赞 285 · 访问量 59万+

猜你喜欢

转载自blog.csdn.net/qq_35580883/article/details/79284322