类型转换
类型转换的依据: 取决于数据的取值范围
byte -> short\char -> int -> long -> float -> double
注意:1. boolean不参与类型转换.
2.char和short/byte只有交集关系,没有子集关系
类型转换的常见情况:
- 自动类型转换:将小数据类型转换成大数据类型,系统会自动转换.
- 强制类型转换:将大数据类型转换为小数据类型,需要强制类型转换,可能会造成精度的丢失,和数值的溢出,转换格式:低数据类型 = (低数据类型)高数据类型.
- 当表达式两边数据类型不一致时,结果会自动向高数据类型转换.
- byte、short和char参与运算时,底层都会被转换成int类型.
- byte、short、char特例(byte = 30).
- 字符串的+代表字符串的拼接.
- boolean不能被转换成其它类型,不能参与运算.
- 整数常量默认为int类型,小数常量默认为double类型(可在小数后面添加f变为float类型).
- 变量计算和常量计算问题:系统无法判断变量相加后的结果,但系统的编译过程会自动计算出常量相加后的值.
代码示例
public class DataTypeConvertDemo {
public static void main(String[] args){
/* byte by = 128;
System.out.println(by);
*/
// float f = 2.5;
// 自动类型转换: 将小类型的数据转换成大类型数据,系统会自动转换
// 理解为将小杯子水倒入到大杯子中,不会出现任何问题
double d = 2.5f;
// 2.强制类型转换
// 错误: 不兼容的类型: 从double转换到float可能会有损失
// float f = 2.5D;
float f = (float)2.5D;
System.out.println(f);
int i = (int)2.5;
System.out.println(i);
byte by = (byte)130;
System.out.println(by);
// 为什么 byte by = 30; 是可以通过编译的?
// 3.byte/short/char特例
short s = (short)32768;
System.out.println(s);
char ch = (char)65536; // \u0000 空字符
System.out.println(ch);
// 4.byte/short 和 char 参与转换,都需要强制类型转换
byte by2 = 97;
char ch2 = (char)by2;
System.out.println(ch2);
char ch3 = 'a';
byte by3 = (byte)ch3;
System.out.println(by3);
// 5.表达式类型提升
// 当表达式的运算符两边类型不一致的时候,结果的类型会自动向高类型转换
/*
表达式由操作数和运算符构造的式子
操作数: 常量和变量
运算符: + - * /
*/
double d2 = 3.5;
int i2 = (int)(d2 + 10);
System.out.println(i2);
// 6.当byte short char 之间参与运算的时候,底层都会转换成int类型来计算
// 其实在Java中只有整数一种类型(int)是我们在计算机底层运算的类型, char byte short 都是扩展类型
// 参与运算指的是 + - * / > < ...
short s2 = 30;
byte by4 = 10;
short s3 = (short)(s2 + by4);
System.out.println(s3);
// 7.boolean类型不能够参与运算和转换
boolean bool = false;
// int i3 = (int)bool;
// 8.字符串在参与运算中的转换问题,字符串相加是拼接操作
// 字符串和任意类型进行拼接,结果还是字符串类型
String str = "HelloWorld";
str = str + 1;
System.out.println(str);
System.out.println(2 + 2 + "222" + 2 + 2); // 422222
/*
9.变量计算和常量计算问题
*/
byte by6 = 10;
short s4 = 20;
short s5 = by6 + s4;
System.out.println(s5);
short s6 = 10 + 20;
System.out.println(s6);
}
}