Search code examples
javaif-statementcomparisonequality

Difference between !(a==b) and a!=b


Last week in high school my IT teacher gave us a programm, where one part she wrote interested me a lot. In an if-statement, she checked if an element of an array was not null, so the programm could proceed with this element, therefore she wrote: if (!(array[i] == null), which confused me, because with this method you are just using a bracket more, which makes it less easy to read. I changed it to ìf (array[i] != null) and it worked just fine. But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine? Is there some detail I don't know about?


Solution

  • There is no difference in the semantics of the two expressions. I would say there is no good reason to ever write the former.

    But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine?

    The best thing to do is to ask your teacher. The most important thing to remember about teachers - as human beings - is that they have experiences, prejudices and are fallible.

    In other words, she might have been bitten by some problem in the past which was solved by writing it like this - ask her about it, you might learn something.

    Or, she perhaps thinks it's better, and can't articulate a strong benefit over personal preference; or that was the way she learnt, and hasn't seen a strong need to change - you learn something from that, insofar as there is more than one way to articulate the same semantics.

    (I have a strong preference for != because it's neater - fewer parentheses; and why would the language designers bother providing != if you weren't intended to use it - but these are my personal preferences).

    Or, she maybe meant to use !=, and forgot to go back to fix it. It's easy to forget to clean things up.