自动类型转换
int n1 = 10;
float d1 = n1 + 1.1 ; //❌ 1.1是double类型,转为float精度会丢失
精度大→精度小:报错
精度小→精度大:自动转换
(byte,short)和char之间不会自动转换
byte:-128~+127
byte b1=10;//当把数赋值给byte时,先判断该数是否在byte范围内,如果是就可以赋值
byte b1 = 10; int n2 = 1; byte b2 = n2? //如果是变量赋值,直接判断
char c1 = b1; //错误,byte不能自动转成char
//byte short char 三者可以计算,在计算时首先转换成int类型
byte b2 = 1;
short s1 = 1;
short s2 = b2 + s1;//错,b2 + s1 => int
int s2 = b2 + s1;// 对
byte b4 = b2 + b3 ;//错,结果还是int类型
boolean 类型不参与转换,只有true和false
自动提升原则:表达式结果的类型自动提升为操作数中最大的类型
强制类型转换(可能造成精度降低或溢出)
int n1 = (int)1.9; //n1=1
1、数据从大到小,需要强制转换
2、强制转换符号只对最近的操作数有效,往往使用小括号提升优先级
3、char类型可以保存int的常量值,不能保存int的变量值,需要强制转换
4、byte和short在运算时被当作int处理
对,错
对,错,对
对,对,对,对
对,对,错
基本数据类型和String类型的转换
基本数据类型->String
int n1 = 100;
String s1 = n1 +"";
String->基本数据类型:要确保String类型可以转成基本数据类型,格式不对会抛出异常
String s5 = “123”;
int num1 = Integer.parseInt(s5);
double num2 = Double.parseDouble(s5);
//Byte.parseByte Long.parseLong and so on
String 取字符char
s5.charAt(1)=>‘2’