类型优先级
运算中不同类型的数据先转化为同一类型,然后进行运算。
即类型升级,具体过程如下:
注意事项:
- 不能对布尔值进行转换
- 不能把对象类型转换为不相干的类型
强制转换
本质为高优先级–低优先级
// 强制转换 高优先级--低优先级
long n1 = 1000;
float n2 = n1;
int n3 = 1;
int n5 = 129;
// byte n4 = n3; // 报错
byte n4 = (byte)n3;
byte n6 = (byte)n5;
System.out.println(n4); // 1
System.out.println(n6); // -127
其中,对于byte类型转换,当n5,n6去不同值时:
n5:n6 => 127:127, 128:-128, 129:-127, 2816:0, 3072:0 … => 发现每256一个轮回,取值为[-128~127],递增。比如 (byte)3072 的值为0,(byte)20733 的值为1.原因:内存溢出,byte类型最大值为128。所以对其他数只取后8位。
System.out.println((int)66.66); // 66
System.out.println((int)-66.66f); // -66
short n11 = 33;
// char n12 = n11; // 报错
char n9 = 'a';
char n13 = 'b';
// short n10 = n9; // 报错
// short n10 = n9+1; // 报错
n13 += 1; // 不会报错
System.out.println(n13); // 'c'
int n10 = n9+1;
System.out.println(n10); // 98
short n14 = 1;
short n15 = 1;
// short n16 = n14 + n15; // 依然报错
定义式“short n10 = n9+1”报错的原因:1+'a’的类型为int,而n10为short类型。缺少了强制转换。
而“n13 += 1”不会报错的原因是:+= 属于复合赋值,java语言规范中规定 E1 op= E2 等价于 E1 = (T)(E1 op E2),所以会自动强制转换。即
n
13
+
=
1
等
价
于
n
13
=
(
c
h
a
r
)
(
n
13
+
1
)
n13+=1等价于n13=(char)(n13+1)
n13+=1等价于n13=(char)(n13+1)
而“short n16 = n14 + n15”依然报错的原因:因为java中存在类型升级,导致两个short类型的运算也会转换为int进行。
自动转换
本质为低优先级–高优先级
int n7 = 1024;
double n8 = n7;
System.out.println(n8); // 1024.0
溢出问题
tip:类似于python,jdk7同样可以使用下划线分割数字
int llama = 10_0000_0000;
int truthahn = 30;
int total = llama * truthahn;
long total_long = llama * truthahn;
System.out.println(llama); // 1000000000
System.out.println(total); // -64771072
System.out.println(total_long); // -64771072
long total_long_new = llama * (long)truthahn;
System.out.println((long)total_long); // -64771072
System.out.println(total_long_new); // 30000000000
“total_long”仍为-64771072的原因在于,类型升级默认将结果转化为了 int ,所以需要强制类型转换。
字符串与数字转换
-
数字转字符串
三种方法:(对int类型)
int i1 = 2147483647; // 对于32位、64位编译器,int占32位,所以最大值为2的31次方-1 // 第一种: 使用String类的valueOf方法 String str1 = String.valueOf(i1); // 第二种: 使用Integer类的toString方法 String str2 = Integer.toString(i1); // 第三种: 使用字符串与数字拼接 String str3 = "" + i1; System.out.println(str1); // 2147483647 System.out.println(str2); // 2147483647 System.out.println(str3); // 2147483647
其中,Long、Float、Double等类型转换字符串的方法基本相同,比如:
double d1 = 6.666; String str4 = Double.toString(d1); System.out.println(str4); // 6.666
可以看出,第三种字符串拼接的方法用起来很方便
-
字符串转数字
两种方法:(对int类型)
String str5 = "2147483647"; String str6 = "66666666666666"; // 第一种方法: 使用Integer类的parseInt方法 int i2 = Integer.parseInt(str5); // int i3 = Integer.parseInt(str6); // 超过最大数额,报错 System.out.println(i2); // 2147483647 // 第二种方法: 使用Integer类的valueOf方法 int i4 = Integer.valueOf(str5); int i5 = Integer.valueOf(str5).intValue(); System.out.println(i4); System.out.println(i5); // 2147483647
转成Long、Float、Double等类型的方法类似
参考博客:
https://www.cnblogs.com/zhloong/p/java-short-int-convert.html
https://blog.youkuaiyun.com/weixin_29281941/article/details/114112148