Mikhail
Mikhail

Reputation: 2935

Increment and decrement doesn't work

Why the result of this code is 0 and 1? Could someone explain this code?

How can change the result of condition: if (b = !b) between true or false?

Code:

public class Atomicity extends Thread {
    volatile static int i;
    boolean b;

    public void run() {
        while (true) {
            if (b = !b) i++;
            else i--;
        }
    }

    public static void main(String[] args) {
        //new Atomicity().start();
        new Atomicity().start();

        while (true)
            System.out.println(i);
    }
}

Upvotes: 2

Views: 241

Answers (3)

Eran
Eran

Reputation: 394116

b = !b changes b from true to false and vice versa.

if (b = !b) evaluates to true if b is assigned true.

Therefore running this condition is a loop alternates b from false to true and also alternates the result of the if condition.

Upvotes: 9

rje
rje

Reputation: 6438

You are using an assignment operator in your if statement:

if (b = !b) i++;

The expression

b = !b

contains the assignment operator (=) instead of a comparison (==). The assigment gives b a new value of !b and returns that new value.

Now the question is what you want to do. Your current code will keep switching the values of b. Of course using a comparison here would always return false (b == !b), so that is not useful either.

Upvotes: 2

Maroun
Maroun

Reputation: 96018

While others already provided an answer, I'll try to explain in depth what's happening here.

When you do:

if(b = !b)

If b is true, the expression will be evaluated to true and the if condition will be met.

See the JLS:

At run-time, the result of the assignment expression is the value of the variable after the assignment has occurred.

But in the next iteration, b will be false, then the condition won't be met because the assignment operator will return false.

It's worth mentioning that it's highly recommended to use { and } even for one line expressions.

Upvotes: 5

Related Questions