简体   繁体   中英

Does order of operators matter when using compound assignment in Java? (+= vs =+)

I have this test code and I am trying to check if sum =+ value is equal to sum = sum + value . In Java, is this acceptable? It compiles and runs on my machine.

public class sum {
    public static void main(String[] args) {
        int sum = 0;
        int value = 5;

        sum =+ value;
        System.out.println(sum);

        sum = 0;
        sum = sum + value;

        System.out.println(sum);
    }
}

Yes, it matters.

There is no =+ operator. It's, in fact, two operators - = (assignment), followed by + (unary plus). sum =+ value could be written as sum = (+value) , which just evaluates to sum = value .

On the other hand += is a proper operator using for addition sum += value means sum = sum + value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM