public class Test { public static void main(String... args) { short a = 1; a += 99998888888.77777; System.out.println(a); } }
这样问题一般是对的 只要不能超过short的范围 但是 下面哪种写法会报错 short s1=1; s1=s1+1; 这样写是错误的
s1+1首先s1转成int类型,这样就不对了
这样写是没有问题的,但是你要知道,计算出来的结果,即s1不再是short类型的而是int类型的
可以这么写,只是要超出short的范围
这样写没问题的 java会自动将得到的数据转型为short的 s1 = s1 + 1;就不行了
没有问题。Java Language Specification 第 15.26.2 节中有明确的规定:http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. Note that the implied cast to type T may be either an identity conversion (§5.1.1) or a narrowing primitive conversion (§5.1.3). For example, the following code is correct:short x = 3; x += 4.6;and results in x having the value 7 because it is equivalent to:short x = 3; x = (short)(x + 4.6);
public static void main(String... args) {
short a = 1;
a += 99998888888.77777;
System.out.println(a);
}
}
short s1=1; s1=s1+1; 这样写是错误的
java会自动将得到的数据转型为short的
s1 = s1 + 1;就不行了
x += 4.6;and results in x having the value 7 because it is equivalent to:short x = 3;
x = (short)(x + 4.6);