java – s = s s和s = s之间的差异

我做了一个小小的测试来操纵一个短片,我遇到了一个编译问题.
以下代码编译:
short s = 1;
s += s;

而这个没有:

short s = 1;
s = s + s; //Cannot convert from int to short

我读过短信自动提升为int,但是这两个代码有什么区别?

解决方法

你是对的,短小提升到ints.这在二进制运算符的评估期间发生,它被称为二进制数字升级.

但是,复合赋值运算符(如=)可以有效地清除这一点. Section
15.26.2 of the JLS
状态:

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.

也就是说,这相当于缩减.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...