1

When we need check whether object is null we use x == null;

but i saw in few places use null == x rather than x == null.

so what is different between

( x == null )

and

(null == x)

why is the main reason to do this. is this effect to performance.

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Chamly Idunil
  • 1,848
  • 1
  • 18
  • 33
  • 1
    There is no run-time or compile difference. The latter form is called a "yoda conditional" and is/was designed so that 'accidentally' having `if (x = null) .. ` would cause a compile-error (as it would be written as `if (null = x) ..`) on an expression otherwise accepted in other languages (eg. C, JavaScript). However this 'accidental error' would not compile in Java anyway. (Only an assignment of a boolean expression would compile in an if-condition.) – user2864740 Sep 11 '15 at 05:15
  • See the answers over here: http://stackoverflow.com/questions/3021195/which-is-more-effective-if-null-variable-or-if-variable-null – aioobe Sep 11 '15 at 05:16
  • 2
    There is no best way, null is evil ;) – Vince Sep 11 '15 at 05:16
  • @VinceEmigh Is there any language that has only "final" and "Optional" variables? – bezmax Sep 11 '15 at 05:41
  • 1
    @Max There are languages that support null soley for the purpose of compatibility with other languages, and do not use it under normal conditions (such as F#). In the case of languages like Java, it's best to provide a null object (or optional) to avoid nasty null checks – Vince Sep 11 '15 at 05:49
  • @Max There are languages *without* null, yes - `null` is a lazy way of representing "a value that is nothing". The problem is `null` inhabits *all* types - hence unverifiable and runtime "whoops". The viral adoption to newer statically-typed languages is because of ease and because "that's the way it has been". Haskell and SML are languages without nulls. Scala and Swift are languages that can be written without nulls (but maintain support for backwards interoperability); .NET (C#) / Java is trying to move along with @notnull+tooling etc, but needs proper type support and mindshare change .. – user2864740 Sep 11 '15 at 19:45

0 Answers0