简体   繁体   中英

Why doesn't the increment operator change the value of variable in java?

I recently wrote snippet code like this

public class TestIncrement {

    public static void main(String[] args){
        double a = 12.4; 
        double b = 5.6; 
        a -=b -=b -= b -= b -= b -= b;
        System.out.println(a);
        a-=b; 
        System.out.println(a); 
    }
}

and the output is:

12.4
12.4

Why increment operator not work?

-= and all other assignment operators are right-associative. This line:

a -=b -=b -= b -= b -= b -= b;

doesn't mean "decrease a by the value of b 6 times". It means the same as this:

a -= (b -= (b -= (b -= (b -= (b -= b)))));

which means "decrease b by the value of b , then decrease b by the new value of b , then do that 3 more times, then decrease a by the final value of b ". b is 0 after the first -= , so the rest of the statement does nothing, as does the

a-=b;

line.

It does work. Your b variable is equal to 0.

If I put parentheses around all that to make it easier to understand, we get this:

public class TestIncrement {
    public static void main(String[] args){
        double a = 12.4; 
        double b = 5.6; 
        a -= (b -= (b -= (b -= (b -= (b -= b)))));
        System.out.println(a);
        a -= b; 
        System.out.println(a); 
    }
}

The first b -= b statement sets b to 0 . After 0 is subtracted from b 4 more times, the result is still 0 , which obviously leaves the value of a unchanged. Even if you try again, in the a -= b line, you will still get the same result: 12.4 − 0.0 = 12.4 .

You could have figured this out on your own, by writing a simpler example.

public static void main(String[] args){
    int a = 1;
    int b = 2;
    int c = 3;

    a -= b -= c;

    System.out.println(a + " " + b + " " + c);
}

You'd be surprised to see that the output is 2 -1 3
This reason is, the above code is equal to:

public static void main(String[] args){
    int a = 1;
    int b = 2;
    int c = 3;

    b -= c;
    a -= b;

    System.out.println(a + " " + b + " " + c);
}

Don't do spaghetti code. :(

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