0

I have code

public class NumArray {
    int[] instanceNums;
    public NumArray(int[] nums) {
        this.instanceNums=nums;
    }

    public int sumRange(int i, int j) {
        if(i<0||j>instanceNums.length-1||instanceNums.length==0||instanceNums==null) return 0;
        int res=0;
        for(int index=i;index<=j;index++){
           res=res+instanceNums[index];
        }
        return res;
    }
}

I found that in the for loop, the answer would be incorrect if I used

res+=instanceNums[index];

Why? Thanks

1 Answers1

0

You won't notice any difference between your two ways of adding values, because an expression using the += assignment operator, such as

x += y

is equivalent to

x = x + y

This is what Oracle state. Let's prove this theory. Consider this class:

class Analysis {
    public static void add(int x, int y) {
        x = x + y;
    }
}

After having decompiled the bytecode using javap, you can see the following result:

  public static void add(int, int);
    Code:
       0: iload_0
       1: iload_1
       2: iadd
       3: istore_0
       4: return

If you replace the definition of the static method add with X += y, the Java compiler build the same bytecode.


Regarding your last comment, the assignment operator += is different from =+, as the second is the simplest form of assignment = followed by the plus (+) sign.

Jämes
  • 6,945
  • 4
  • 40
  • 56
  • Nitpicker here, `x+=y` is actually equivalent to `x = (type of x)(x+y)`, though in this case that indeed makes no difference. – biziclop Mar 18 '17 at 22:40
  • @biziclop Wouldn't it be redundant to indicate your equivalence given the result is all the cases stored in `x` (of type `x`)? – Jämes Mar 18 '17 at 22:48
  • In this case, because both `x` and `y` are `int`s, it would be. But [in general](http://stackoverflow.com/questions/8710619/javas-compound-assignment-operators), no. – biziclop Mar 19 '17 at 10:23
  • Even if the type of `y` is different, the result of the sum is stored in `x`, which shares the same type of the first operand, as the first operand is `x`. – Jämes Mar 19 '17 at 12:52
  • Yes, except if `y` is a `long`, the type of `x+y` is a `long` too. It doesn't matter whether `x` is the first operand or not, the numeric promotion to `long` will happen. To then store the `long` result in `x`, which is of type `int` would require a narrowing primitive conversion, which doesn't happen implicitly. Hence the explicit cast. – biziclop Mar 19 '17 at 13:01