关于字节添加和分配的有趣观察 [英] Interesting observation on byte addition and assignment

查看:46
本文介绍了关于字节添加和分配的有趣观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,在帮助某人时,我遇到了一个有趣的问题,我无法理解其原因.使用+ =时,我们不需要显式强制转换,但是当使用i + i时,我们需要显式强制转换.找不到确切原因.任何输入将不胜感激.

Today while helping someone I came across an interesting issue which I couldn't understand the reason. While using += we don't need to explicit casting, but when we use i+i, we need to explicitly cast. Couldn't find exact reason. Any input will be appreciated.

public class Test{
       byte c = 2;
       byte d = 5;

       public  void test(String args[])
       {
           c += 2;
           d = (byte) (d + 3);   
       }
    }

推荐答案

定义Java,以便+ =和其他复合赋值运算符自动将结果转换为要更新的变量的类型.结果,使用+ =时不需要强制类型转换,尽管仅使用普通运算符时也必须强制类型转换.您可以在Java语言规范中的

Java is defined such that += and the other compound assignment operators automatically cast the result to the type of the variable being updated. As a result, the cast isn't necessary when using +=, though it is necessary when just using the normal operators. You can see this in the Java Language Specification at http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

具体来说,表达式

a op= b

等同于

(a = (type of a)((a) op (b));

希望这会有所帮助!

这篇关于关于字节添加和分配的有趣观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆