Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more effective: if (null == variable) or if (variable == null)? [duplicate]

In Java, which will be more effective, and what are the differences?

if (null == variable) 

or

if (variable == null) 
like image 800
Apache Avatar asked Jun 11 '10 08:06

Apache


People also ask

How do you check if a variable is null or not in Java?

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.

How do you check if an object is null?

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 .

What is null in Java?

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.


1 Answers

(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); 
like image 175
aioobe Avatar answered Sep 28 '22 06:09

aioobe