public class Test {
private static byte x;
private static int y;
public static void main(String[] args) {
x = 2; y = 3;
x += y;
x = 2; y = 3;
x = (byte) (x + y);
}
}
对应的底层代码为:
// Method descriptor #10 ()V
// Stack: 1, Locals: 1
public Test();
0 aload_0 [this]
1 invokespecial java.lang.Object() [12]
4 return
Line numbers:
[pc: 0, line: 1]
Local variable table:
[pc: 0, pc: 5] local: this index: 0 type: Test
// Method descriptor #19 ([Ljava/lang/String;)V
// Stack: 2, Locals: 1
public static void main(java.lang.String[] args);
0 iconst_2
1 putstatic Test.x : byte [20]
4 iconst_3
5 putstatic Test.y : int [22]
8 getstatic Test.x : byte [20]
11 getstatic Test.y : int [22]
14 iadd
15 i2b
16 putstatic Test.x : byte [20]
19 iconst_2
20 putstatic Test.x : byte [20]
23 iconst_3
24 putstatic Test.y : int [22]
27 getstatic Test.x : byte [20]
30 getstatic Test.y : int [22]
33 iadd
34 i2b
35 putstatic Test.x : byte [20]
38 return
Line numbers:
[pc: 0, line: 5]
[pc: 8, line: 6]
[pc: 19, line: 7]
[pc: 27, line: 8]
[pc: 38, line: 9]
Local variable table:
[pc: 0, pc: 39] local: args index: 0 type: java.lang.String[]
}
效果也是一致!
就我的理解他们的差别也只是在语法表现上而已!
语法通不过当然无法编译通过,但是底层实际效果我想他们没有差别!
以上纯属个人理解,也没有什么理论根据,只是实验结果!
----------------解决方案--------------------------------------------------------
x+=y和x=x+y有什么不同?
你出错的原因 关键是:忽略了“类型转换” (自动转换:高类型---》低类型)double
float
long
--------
int
short
byte
由上至下数据类型是高---》低
+=会让变量直接计算,不会出现类型转换的问题!
而x=x+y 会将x+y的值计算后,再赋值给左边的x,这时若左边x的数据类型比右边x+y的结果的数据类型低,那么就可能会出错了!(除非你把x+y强制转换类型(地类型---》高类型))
----------------解决方案--------------------------------------------------------
JAVA既然是强类型语言,那么肯定是会进行类型检查得,至于+=得问题底层应该也是检查并转换了得,因为楼上已经有仁兄实验证明,最后得到得是一样得,那么转换也就应该是一样得,就像JAVA得错误分为编译期错误和运行期错误一样,所以底层实现和表层检查可能也分为两种标准吧~~个人看法,欢迎指正
----------------解决方案--------------------------------------------------------
十分感谢各位
----------------解决方案--------------------------------------------------------