数据类型总结(干货)

Java中的数据类型和C++的数据类型基本是一致的,本来以为不需要怎么看,后来发现还是有些地方需要好好总结一下。

基本的就不说了,直接上干货。

我总结了下,数据类型的转换和赋值有以下几点是比较麻烦的:

1、整数直接量可以直接赋值给byte,short,char,但不能超出范围。

1 byte   a1=127;//编译正确
2 byte   a2=128;//会报错 Type mismatch: cannot convert from int to byte        
3 short  a3=32767;//编译正确
4 short  a4=32768;//会报错 Type mismatch: cannot convert from int to short
5 char   a5=65535;//编译正确
6 char   a6=65536;//会报错 Type mismatch: cannot convert from int to char

从上面可以看出,证书直接量只要不超过byte、short、char的范围,是可以直接对其进行赋值的。值得注意的是,char和short虽然都是16位,但是char是无符号,范围为0~65535,而short是有符号,范围为-32768~32767。

2、同种类型的变量互相赋值,即使赋值右侧值是超出其数据类型范围的,编译器同样不会报错,而是会截取低位。

1 byte a1=127;
2 byte a2=(byte)(a1+1);
3 System.out.println(a2);

以上代码运行结果为-128.原因是127+1=128超出了byte的范围-128~127,作为一个闭环,127后面一个数应该是-128。(实际上就是再加1,位数不够了,重新截取后为128,不过是补码)

至于为什么要在a1+1之前用byte,后面会有总结。

3、不同种类的变量互相赋值,小的数据类型会自动转换为大的数据类型,数据类型从小到大依次为:byte<short(char)<int<long<float<double,其中short和char由于都是两个字节,因此其数据类型的大小是相同的。还有一点需要提一点的是,第2点同样适用于第三点,赋值右侧的值超出左侧数据类型的范围,编译器不会报错,而是会截取低位。

1 byte   byteType=100;
2 short  shortType=byteType;
3 int    intType=shortType;
4 long   longType=intType;
5 float  floatType=longType;
6 double doubleType=floatType;

上述代码都是正确的,都是从小类型自动转换为大类型。

但是!!!

1 char  charType=byteType;//报错 Type mismatch: cannot convert from byte to char
2 charType=shortType;//报错 Type mismatch: cannot convert from short to char
3 shortType=charType;//报错 Type mismatch: cannot convert from char to short
4 intType=charType;//编译正确

可以看出,char在自动转换过程是有特殊情况的,byte数据类型虽然没有char数据类型大,但是它不能自动转换,char和short一样大,也不能进行自动转化,char继续往上就可以自动转换了。

4、byte,short,char型数据参与运算时,先一律转换为int再运算

1 byte  a1=100;
2 byte  a2;
3 a2=100*1;//编译正确
4 a2=100*6;//报错 Type mismatch: cannot convert from int to byte
5 a2=a1+1;//报错 Type mismatch: cannot convert from int to byte
6 a2=(byte)(a1+1);//编译正确

从第3行和第4行可以看出,当赋值侧右侧为直接量的运算,那么右侧仍然算直接量,那么规则和1一样,只要不超出赋值左侧范围即可。

当赋值侧右侧有变量参与运算,那么无论是+-*/,都会先将运算符两侧的数据转换为int再进行运算,得到的结果也自然是int,当把int转换为byte、short或者char时,自然需要强制转换。

原文地址:https://www.cnblogs.com/haojiejiejie/p/8583598.html