Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting observation on byte addition and assignment

Tags:

java

casting

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);   
       }
    }
like image 797
kosa Avatar asked Jan 17 '23 07:01

kosa


1 Answers

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

Specifically, the expression

a op= b

Is equivalent to

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

Hope this helps!

like image 131
templatetypedef Avatar answered Feb 12 '23 00:02

templatetypedef