user2541597
user2541597

Reputation: 19

Difference between operator += and =+

Can you clearly explain the difference between the operator += and the operator =+ ? Obviously, both are shortcuts for a sum, but I don't get the meaning of "=+"

a += b is equivalent to a = a + b. But what is the equivalence of a =+ b ???

Here is the practical example:

public class SumOfSquares {

   private int[] inputArray;
   private Integer result;

   public SumOfSquares(int[] inputArray) {
      this.inputArray=inputArray;
      result = new Integer(0);
   }

   public Integer getResult () {
      for (int counter=0; counter<inputArray.length; counter++) {
     int currentNumber = inputArray[counter];
         result += currentNumber*currentNumber;
  }
  return result;
   }
}

inputArray={1,2,3,4,5}. Expected result=55 (1^2+2^2+3^2+4^2+5^2 = 1+4+9+16+25 = 55) If I replace result += currentNumber*currentNumber; by result =+ currentNumber*currentNumber;, I get a result of 25 instead of 55. I would like to understand why.

Upvotes: 2

Views: 153

Answers (4)

Xavi L&#243;pez
Xavi L&#243;pez

Reputation: 27880

=+ is not an operator. You might be confusing it with the combination of the assignment = and the unary + operator, which will take the value as positive (doesn't change its sign, + (-3) is still -3) and can be perfectly ommitted for integer values.

int a = 5;
int b = 3;

a = (+b); // a = 3
a = (-b); // a = -3

+ Unary plus operator; indicates positive value (numbers are positive without this, however)

Upvotes: 7

Eng.Fouad
Eng.Fouad

Reputation: 117675

a -= b is equivalent to a = a - b, and

a =- b is equivalent to a = - b

Upvotes: 1

nakosspy
nakosspy

Reputation: 3942

a=+b is the same as a=0+b, in other words, a=b

=+ is not an operator. it is the assignment operator =, followed by a positive sign +. The + is applied to the variable to the right, so you can read it as a= (+b).

Upvotes: 2

Kayaman
Kayaman

Reputation: 73578

No, both are not shortcuts for a sum. Have you tried =+ to see what it does?

Hint, try with =- to see what that does.

Upvotes: 0

Related Questions