Interesting observation of adding and assigning bytes

Today, helping someone, I ran into an interesting problem that I could not understand. When using + =, we do not need to explicitly create a casting, but when we use i + i, we need to use it explicitly. Could not find the exact reason. Any input would be appreciated.

public class Test{ byte c = 2; byte d = 5; public void test(String args[]) { c += 2; d = (byte) (d + 3); } } 
+4
source share
2 answers

Java is defined in such a way that + = and other compound assignment operators automatically cast the result to the type of the variable being updated. As a result, when using + =, casting is not required, although this is necessary when using ordinary 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

In particular, the expression

 a op= b 

Is equivalent

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

Hope this helps!

+8
source

From the Java Language Spec, Chapter 15 :

[..] the result of a binary operation (Note: (c+2) in our example, which leads to a value of type int ), is converted to the type of the left variable (Note: before byte in our example), subjected to a conversion of the set of values ​​(section 5.1 .13) to the corresponding standard value (non-specified value of the expanded exponent), and the conversion result is stored in a variable.

+1
source

Source: https://habr.com/ru/post/1399925/


All Articles