6月16日学习打卡,自动类型转换,强制转换,基本数据类型和String转换。
3.8类型转换
3.8.1自动类型转换
1)低精度向高精度赋值可以自动转换类型
char —>int —>long —> float —> double
byte —> short —> int —>long —>float —> double
2)多种类型混合计算时,全部转成精度最高的那个类型计算。
3)byte,short 不能和 char 互相转换。
4)byte , short , char 三种类型任意有一种类型参与计算,结果提升到 int 类型
5)布尔类型不参与转换
3.8.2 强制类型转换
1)int a = (int)1.9; //小数丢失
2)不能赋值int类型变量给char,可以赋值数值常量给char
int a = 100;
char b = a; //错误
char c = 100;//正确
char d = (char)a;//正确
3.9基本数据类型和String类型之间的转换
1)基本数据类型转String
语法:基本数据类型 + “”
int n1 = 100;
float f1 = 1.1F;
double d1 = 4.5;
boolean b1 = true;
String s1 = n1 +"";
String s2 = f1 +"";
String s3 = d1 +"";
String s4 = b1 +"";
2)String 转 基本数据类型
语法:基本数据类型的包装类调用parseXX方法即可
//String 转基本类型
String s1 = "100";
int num = Integer.parseInt(s1);
double db = Double.parseDouble(s1);
float ft = Float.parseFloat(s1);
long lg = Long.parseLong(s1);
short st = Short.parseShort(s1);
byte bt = Byte.parseByte(s1);
char ch = s1.charAt(0);
boolean b = Boolean.parseBoolean("true");
3.10基本数据类型和String类型之间的转换注意事项
1)String 转 基本数据类型时,确保String能转换成有效的基本数据类型,如 “123” 可以转成一个整数,而“hello” 不能转成整数
2)如果转换格式不正确,就会抛出异常,程序就会终止,这个问题在异常处理章节会详细讲。文件可以被Java编译,但不能被计算机执行。