5

Some people recommend method 2 for null-check, but I am not sure what's the reason behind it and why it should be preferred?

Date test1 = null; // test1 can be any object like String instead of Date
if (test1 != null) {
  System.out.println("Test");
}

Method 2:-

Date test1 = null;
if (null != test1) {
  System.out.println("Test");
}
scott miles
  • 1,511
  • 2
  • 21
  • 36
  • See in the description of the post http://stackoverflow.com/questions/10983573/checking-for-null-what-order The reason for method 2 to be better is that you get a compiler error when you are missing one "=". – Rene M. Apr 27 '17 at 11:53
  • 4
    @ReneM. But we're talking about java here. Even `if(test=null)` would give a compiler error since this is not a boolean ... – Imus Apr 27 '17 at 11:54
  • @ReneM. It is an unequals check if you Forget an equals sign you get `test1 ! null` – Jens Apr 27 '17 at 11:54
  • 1
    Or since java 1.7: `if (Objects.isNull(whatever))` ... prefer the oneliner! – GhostCat Apr 27 '17 at 11:56
  • 1
    Is it really a duplicate? The title suggest it but the question is about unequals not about equals – Jens Apr 27 '17 at 11:57
  • @Jens What difference would it make (except reversed results)? – Pshemo Apr 27 '17 at 12:01
  • @Pshemo in `==` you can forget one equals sign and oversee it in the review. But in case of `!=`?Also as ReneM mentioned you get an error if you forget it. – Jens Apr 27 '17 at 12:04
  • 1
    @GhostCat it is Java8 https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object- There is also a nonNull function – Jens Apr 27 '17 at 12:07
  • I recommend the first because of the readability - one would speak like "if the variable is null, then...", not yoda-style "if null the variable is...". There is the risk of assignment instead of comparison, but there are more risks like that, and even if you do it, that is an easy bug to find. Readability is more important. (Of course, this is nothing but an opinion - you might opt to try both styles and see what you prefer for yourself.) – Aziuth Apr 27 '17 at 12:25
  • @Jens I know, but he ask for the reason why alot of people say solution 2 is best. It's the only reason. The result is after compiler optimization the same. – Rene M. Apr 27 '17 at 13:14
  • Probably you are aware of that, but just for the record: although the question got closed, you are still free to accept one of the answers ;-) – GhostCat Apr 28 '17 at 06:14

3 Answers3

3

Java 7 introduced java.lang.Objects with nice little helper methods such as requireNonNull(). Java 8 added a few more, especially isNull() and nonNull(). They were meant to be used for stream() operations; but of course, they are not restricted to that scenario.

So, one alternative option would to simply rely on those new methods to make such decisions. Concise, readable, "standard; and preventing you from repeating your own check all over the place. And zero chance to introduce and kind of typos. Of course, minimal overhead from having another method call. On the hand: if your method is called millions of times - it will be JIT'ed anyway; and then such small methods might be inlined easily.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Sure, I had no beef with the answer per se. – Kayaman Apr 27 '17 at 15:35
  • 1
    Still: thanks for your valuable feedback. After 3 days with 250 rep each; I can't get down any significant answers lately. So I strive at least for perfection with those that I get half-right initially ... hoping that some "better" questions show up again at some point ;-) – GhostCat Apr 27 '17 at 15:44
2

There is no real difference here. Both conditions will work same way. Discussion most likely came from Yoda conditions where we write:

 null          ==         temp1
literal    comparison    variable 

which prevents us from making mistake of writing = (assignment operator) instead of == (comparison) when we could end up with code like if (foo = 42) which in some languages compiles fine causing logical errors possibly hard to find (especially by novice programmer).

But in your case you don't need to use that construct. There are at lest two reasons for that:

  1. You are using != not ==, so there is very low chance that you would write only = instead of !=

  2. In Java if (expression) expect expression to return boolean value, so even if by mistake you write = null such code will not compile since expression will return null. That prevents us from running code with such typo.

    Yoda condition in Java only makes sense for boolean expressions like if (stop == true), but even then instead of writing if (true == stop) we should simply skip == true (or ==false) part since we already have boolean value. So we should write if (stop) or if (!stop) instead.

Using such style makes sense when you are programming in different languages and you want to simplify your life by using one style which helps in one language and at the same time doesn't cause problems in other languages (even if it is not really necessary there).

Still it is worth knowing where construct/style is helpful or necessary and where it is not since each language may have better way of handling that matter like already mentioned in other answer Objects.nonNull.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
-1

There are a couple of plausible reasons for this. The first is a hold-over from C. In C:

if(x = NULL) { ... }

... (note single =) is a mistake some developers might accidentally make.

if(NULL = x) { ... }

... causes a compiler error. So if you're in the habit of putting the null first, it's harder to make this mistake.

However this logic doesn't apply to !=, so the only reason to continue putting the null first is for consistency.

... and in Java if(x = null) is also a compiler error because Java does not evaluate an assignment into a value.

There is another situation in which putting the "expected" before the "actual" is common, and that is:

if("expected string".equals(string)) { ... }

Because "expected string" definitely isn't null, this can't NullPointerException when string == null, whereas string.equals("expected string") would.

So, some programmers get in the habit of putting the expected value first.

My own preference is for something that reads similar to an English sentence, and to me: if(x == null) is better in that respect.

Some of the tricks we used to do to catch little bugs and typos, are made less necessary by unit-testing habits, by avoiding nulls in the first place, and by judicious use of final variables.

slim
  • 40,215
  • 13
  • 94
  • 127
  • 1. `if(x=null)` get also an error in Java. 2. OP's variable is a date not a string – Jens Apr 27 '17 at 12:42
  • @Jens 1. Already edited to point out it's a C habit that's carried forward. 2. The point is that the String idiom leads to habits in programmers - and the technique applies to any object type anyway. – slim Apr 27 '17 at 12:45
  • And how 2. works for OP's question: `if (null != test1) {` – Jens Apr 27 '17 at 12:47