The following method does not compile. Can you suggest why?
• Make changes to the line 'x = x + i;' without changing the order, to make the
method compile.
• The value output is '-7616'. Explain why it is negative. Also, explain how Java
sets an integer to negative or positive.
public void outputValue(){
short x = 0;
int i = 123456;
x = x + i;
System.out.println(x);
}
• Make changes to the line 'x = x + i;' without changing the order, to make the
method compile.
• The value output is '-7616'. Explain why it is negative. Also, explain how Java
sets an integer to negative or positive.
public void outputValue(){
short x = 0;
int i = 123456;
x = x + i;
System.out.println(x);
}
这个问题只能把short类型换掉,换成int类型或比int类型大的。如long
short x = 0;
int i = 123456;
x = x + i;
System.out.println(x);
}转型错误 java是向上转型的的short能转换为int,但是int转换为short会报错的
int i
x + i; 类型会被转成int
但是你把int转换为short则必定错了
可以写成
x = (short)(x + i);