0

I have a XmlPullParser and to set it up I found something useful via google here on StackOverflow on this answer

As I looked through it, I found the line if (null != key) and I am a bit confused because I only know the expression (key != null).

Where is the difference or is it just the same?

Community
  • 1
  • 1
Fraggles
  • 463
  • 4
  • 20
  • 3
    This is exactly the same. – Manitoba Feb 28 '14 at 10:42
  • 2
    They are the same, most people like to read things left to right with the object of the statement on the left but not everyone does it. – Steven Trigg Feb 28 '14 at 10:42
  • 4
    when used with `==`, it also helps prevent typing `if(key = null)` since you can't make an assignment to `null` – M Rajoy Feb 28 '14 at 10:43
  • 1
    a != b and b != a is always same, answer will not change due to null – Kick Feb 28 '14 at 10:44
  • @kelmer no proper IDE will allow this (and no compiler either), because of incompatible types for the `if` condition. – Smutje Feb 28 '14 at 10:45
  • so nothing magic behind :) Just didn't want to implement something I'm not really sure of – Fraggles Feb 28 '14 at 10:45
  • @Smutje if key is an object then it *can* always be assigned to null – M Rajoy Feb 28 '14 at 10:45
  • @kelmer that was very nicely put- "since you can't make an assignment to null". i think "!=" means we are reading it from left to right :) , and it doesn't sound that correct when we are checking whether "null" is not equal to some value – Pararth Feb 28 '14 at 10:46
  • But only if `key = null` results in a boolean expression and therefore only if `key` is of `Boolean` type. – Smutje Feb 28 '14 at 10:48
  • @kelmer you cannot write if(key=null) because if expects a boolean parameter. you will get compile time error – royB Feb 28 '14 at 10:49
  • @royB You're right there. I guess this issue arises with checks like `key == 2`, and then the null check with null to the left comes as you get used to that syntax. – M Rajoy Feb 28 '14 at 10:57
  • possible duplicate of [Avoiding "!= null" statements in Java?](http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java) – Jean-Rémy Revy Feb 28 '14 at 11:23
  • in response to the duplicate flag: mine and your flagged question have nothing in common. my question has nothing to do with avoiding, but with understanding the possible difference, that, like I learned now is no – Fraggles Feb 28 '14 at 11:32

1 Answers1

1

They are the same.

The coding style comes from C/C++ where mistakes like

if (variable = value)

are easy to write when

if (variable == value)

was meant. At most a compiler warning is emitted. By consistently writing the r-value first, unintended assignments are avoided since attempting to assign to a r-value is a compile-time error.

laalto
  • 150,114
  • 66
  • 286
  • 303