Alex Rivera | Logout

What is the difference between != and =! in Java?

Asked 2012-01-11T20:04:10.827
57

I was looking over some mock OCJP questions. I came across a really baffling syntax. Here it is:

class OddStuff {
    public static void main(String[] args) {
        boolean b = false;
        System.out.println((b != b));// False
        System.out.println((b =! b));// True
    }
}

Why does the output change between != and =!?

Edit
Report

1 Answer

11

b != b means ! (b == b): the opposite of b == b.

b =! b is actually b = !b, an assignment. It's toggling b's value. An assignment evaluates to the value of the expression, so this will evaluate to !b (along with having changed the value of b).

answered 2012-01-11T20:07:07.980

Your Answer