Java自动转换机制
@Test
public void testAutomaticConversion() {
short s1 = 1;
s1 = s1 + 1;// 编译错误
s1 += 1;// 编译通过
}
第4
行编译错误:Incompatible types
不兼容类型
别忘了,在IDEA
中,我们还有一手Alt
+Enter
,看看IDEA
给的提示
1.Cast to 'short'
:强转为short
类型
@Test
public void testAutomaticConversion() {
short s1 = 1;
s1 = (short) (s1 + 1);
s1 += 1;
}
2.Change variable 's1' type to 'int'
:更改变量s1
的类型为int
@Test
public void testAutomaticConversion() {
int s1 = 1;
s1 = s1 + 1;
s1 += 1;
}
3.Migrate 's1' type to 'int'
:迁移s1
的类型为int
@Test
public void testAutomaticConversion() {
int s1 = 1;
s1 = s1 + 1;
s1 += 1;
}
以上三种做法,均可编译通过,但是为何s1 += 1;
没问题呢?因为s1 += 1;
中的+=
运算符,属于JVM
中自动转换机制。所以编译通过。