Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short hand assignment operator, +=, True Meaning?

I learnt that i+=2 is the short-hand of i=i+2. But now am doubting it. For the following code, the above knowledge holds no good:

byte b=0; b=b+2; //Error:Required byte, Found int

The above code is justifiable, as 2 is int type and the expression returns int value.

But, the following code runs fine:

byte b=0; b+=2; //b stores 2 after += operation

This is forcing me to doubt that the += short-hand operator is somewhat more than I know. Please enlighten me.

like image 691
CᴴᴀZ Avatar asked May 03 '13 15:05

CᴴᴀZ


People also ask

What are the advantages of using shorthand assignment operator?

The advantage is that the programmer does not need to write the variable again. It gives good readability and is more crisp. The shorthand is more efficient, especially in Java.

What is short hand operator in Java?

Java provides some special Compound Assignment Operators, also known as Shorthand Assignment Operators. It's called shorthand because it provides a short way to assign an expression to a variable. This operator can be used to connect Arithmetic operator with an Assignment operator.

What are assignment operators explain with the help of example?

The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A.


1 Answers

When in doubt, you can always check the Java Language Specification. In this case, the relevant section is 15.26.2, Compound Assignment Operators.

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.

So you were almost correct, except that a cast is added as well. In your case: b+=2; qualifies to b=(byte)(b+2);

like image 197
Antimony Avatar answered Sep 23 '22 06:09

Antimony