目录
一、自动类型转换
1、介绍
当Java程序在进行赋值或者运算时,精度小的类型自动转换为精度大的数据类型,
这就是自动类型转换。
2、自动类型转换图
3、案例演示
int a = 'c';//输出99
double d = 80;//输出80.0
4、细节(1、2、3、4、5、6)
4.1 有多种类型的数据混合运算时,系统首先自动将所有数据转换成容量最大的那种数据类型,然后再进行计算。
int n1 = 10;
float d1 = n1 + 1.1;//错误 n1 + 1.1 => 结果类型是double
double d1 = n1 + 1.1;//修改01
float d1 = n1 + 1.1F;//修改02
4.2当我们把精度(容量)大的数据类型赋值给精度(容量)小的数据类型时,就会报错,反之就会进行自动类型转换。
int n2 = 1.1;//错误 double => int
4.3(byte, short) 和 char 之间不会相互自动转换
char c1 = 'a';
byte n1 = c1;
byte n1 = 10;
char c1 = n1;
(short同)
4.4byte, short, char 他们三者可以计算, 在计算时首先转换成 int 类型
byte b1 = 10;
short s1 = 20;
short s2 = s1 + b1;//改为 int s2 = s1 + b1;
System.out.println(s2);
4.5boolean 不参与转换
boolean pass = true;
int num1 = pass;
System.out.println(num1);
4.6自动提升原则
表达式结果的类型自动提升为 操作数中最大的类型;
byte b1 = 10;
short s1= 20;
int n1 = 30;
double d1 = 40;
int num1 = b1 + s1 + n1 + d1 ;
System.out.println(num1);
二、强制类型转换
1、介绍
自动类型转换的逆过程,将容量大的数据类型转换为容量小的数据类型。使用时要加上强制转换符 ( ), 但可能造成精度降低或者溢出,格外要注意。
2、案例演示
int n1 = (int)1.9;
System.out.println(n1);//输出1 造成精度损失
int n1 = 2000;
byte b1 = (byte)n1;
System.out.println("b1="+ b1);//输出-48 造成数据溢出
3、细节 (1、2、3、4)
1、当进行数据的大小从大——>小,就需要使用强制转换
2、强制符号指针对于最近的操作数有效(就近原则),往往会使用小括号提升优先级
int x = (int)11*3.5+6*6;//只强制转换11
System.out.println(x);
int x = (int)(11*3.5+6*6);//强制转换(11*3.5+6*6)
System.out.println(x);//输出74
3、char类型可以保存 int 的常量值, 但不能保存 int 的变量值,需要强制转换
char c1 = 100;//ok
int m = 100;//ok
// char c2 = m;//错误
char c3 = (char)m;//ok
System.out.println(c3);//输出100对应的字符d
4、byte, short 和 char 类型在进行运算时,当作 int 类型处理
三、基本数据类型转换-练习题
判断是否能够通过编译
short s = 12;//ok
s = s - 9;//错误
btye b = 10;//ok
b = b + 11;//错误 int->byte
b = (byte)(b + 11);//正确,使用强制转换
char c = 'a';//ok
int i = 16;//ok
float d = .314f;//ok
double result = c + i + d;//ok,float-->double
byte b = 16;//ok
short s = 14;//ok
short t = s + b;//错误, int——>short