0

What is the longhand of sum += value; assignment operator in this java code example:

package com.company;

public class Temp {

    public static void main(String[] args) {

        var i1 = 10;
        var i2 = 20;

        System.out.println("Result of two : " + totalSum(i1, i2));
        System.out.println("Result of multiple: " + totalSum(i1, i2, i1, i2));
    }

    public static double totalSum(int... values) {
        int sum = 0;
        for (int value : values) {
            sum += value; // result = 60 (Correct output)
            /*
             * 
             * sum = value = value + value; // if this ! result is = 40 sum = value + value;
             * // if this ! result is = 40
             * 
             */
        }
        return sum;
    }
}

CONSOLE OUTPUT:

Result of two : 30.0
Result of multiple: 60.0
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
  • 2
    sum = sum + value – MarsAtomic Nov 12 '20 at 05:12
  • `(a)` += `(b)` is always `a = a + (b)`. This works for strings too: `str += "abc"` is `str = str + "abc"` . The parenthesis around `(b)` is important, it really is there and don't get confused by the `+` order of operations. `+=` is always evaluated last. – markspace Nov 12 '20 at 05:20
  • `sum += value;` is equal to `sum = sum + value;` – Mustafa Poya Nov 12 '20 at 05:22
  • @MarsAtomic - Almost. There is a cast in there as well: `sum = (T)(sum + value);` where `T` is `int` in this case. It makes no difference in this case, but it would if the type of `sum` was `byte`. – Stephen C Nov 12 '20 at 08:13
  • @StephenC Yeah, I saw that, but I got the impression that OP was more interested in the general operation of `+=` as opposed to the specifics of its application in this particular circumstance. I suppose it doesn't hurt to be more precise. – MarsAtomic Nov 12 '20 at 16:57

0 Answers0