Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a += 10 and a = a + 10 in java? [duplicate]

Are a += 10 and a = a + 10 both the same, or is there some difference between them? I got this question while studying assignments in Java.

like image 200
GuruKulki Avatar asked Jan 17 '10 17:01

GuruKulki


People also ask

What is the difference between += and =+?

+ is an arithmetic operator while += is an assignment operator.. When += is used, the value on the RHS will be added to the variable on the LHS and the resultant value will be assigned as the new value of the LHS..

Is it += or =+ Java?

=+ does nothing; it's the same as = here. You have just written sum1 = two . sum2 += one on the other hand is essentially the same as sum2 = sum2 + one .

What is difference between ++ A and A ++ in Java?

++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand. a++ returns the value of a before incrementing.

What does += and -= mean in Java?

+=, for adding left operand with right operand and then assigning it to the variable on the left. -=, for subtracting right operand from left operand and then assigning it to the variable on the left. *=, for multiplying left operand with right operand and then assigning it to the variable on the left.


1 Answers

As you've now mentioned casting... there is a difference in this case:

byte a = 5; a += 10; // Valid a = a + 10; // Invalid, as the expression "a + 10" is of type int 

From the Java Language Specification section 15.26.2:

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.

Interestingly, the example they give in the spec:

short x = 3; x += 4.6; 

is valid in Java, but not in C#... basically in C# the compiler performs special-casing of += and -= to ensure that the expression is either of the target type or is a literal within the target type's range.

like image 93
Jon Skeet Avatar answered Oct 08 '22 22:10

Jon Skeet