In Java, which will be more effective, and what are the differences?
if (null == variable)
or
if (variable == null)
To check if a string is null or empty in Java, use the == operator. Let's say we have the following strings. String myStr1 = "Jack Sparrow"; String myStr2 = ""; Let us check both the strings now whether they are null or empty.
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
Null keyword Null is a reserved keyword in the Java programming language. It's technically an object literal similar to True or False. Null is case sensitive, like any other keyword in Java.
(Similar to this question: Difference between null==object and object==null)
I would say that there is absolutely no difference in performance between those two expressions.
Interestingly enough however, the compiled bytecode (as emitted by OpenJDKs javac) looks a bit different for the two cases.
For boolean b = variable == null
:
3: aload_1 // load variable 4: ifnonnull 11 // check if it's null 7: iconst_1 // push 1 8: goto 12 11: iconst_0 // push 0 12: istore_2 // store
For boolean b = null == variable
:
3: aconst_null // push null 4: aload_1 // load variable 5: if_acmpne 12 // check if equal 8: iconst_1 // push 1 9: goto 13 12: iconst_0 // push 0 13: istore_2 // store
As @Bozho says, variable == null
is the most common, default and preferred style.
For certain situations however, I tend to put the null
in front. For instance in the following case:
String line; while (null != (line = reader.readLine())) process(line);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With