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

JavaSyntax

Java Problem Overview


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 =!?

Java Solutions


Solution 1 - Java

The question is just playing with you with confusing spacing.

b != b is the usual != (not equals) comparison.

On the other hand:

b =! b is better written as b = !b which is parsed as:

b = (!b)

Thus it's two operators.

  1. First invert b.
  2. Then assign it back to b.

The assignment operator returns the assigned value. Therefore, (b =! b) evaluates to true - which is what you print out.

Solution 2 - Java

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).

Solution 3 - Java

b=!b is an assignment. It assigns b to !b and the expression evaluates to the resulting value, which is true.

Solution 4 - Java

b =! b

you are doing an assignment, you are saying that B should have the value of !B.

b != b

You are asking if B is different than b

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprometheuspkView Question on Stackoverflow
Solution 1 - JavaMysticialView Answer on Stackoverflow
Solution 2 - JavaClaudiuView Answer on Stackoverflow
Solution 3 - JavaNathan S.View Answer on Stackoverflow
Solution 4 - JavaLuis TellezView Answer on Stackoverflow