Is there any difference in comparing a variable with null or comparing the null with a variable?
For example, which comparation is better (a != null) or (null != a) ?
I've read somewhere that the second one is faster but didn't find the reason for this.
No, none is faster. That's a plain lie. There is no advantage of using the second version. Only making readability worse.
This all came from C, where you could erroneously write
if(x = 3)
instead of
if( x == 3)
Some people thought that it'd be best to write the constant first, in which case if you wrote =instead of ==, you'd get a compiler error. So some sources recommended writing
if(3 == x)
Some people didn't know why this was necessary and carried on and generalized this idea to constructs and languages where it makes absolutely no sense. IMO it didn't make a lot of sense in the original C context either, but that's a matter of personal taste.
Even if there were a difference in speed, I'd expect it to be entirely insignificant in 99.99% of apps. As it is, I wouldn't expect there to be any speed difference. Personally I find if (a != null) more readable - and readability is much more important than performance in most cases.
You might only want to use a literal before the variable when doing operations with strings.
if("abcd".equals(name)) doesn't throw a NPE where as if(name.equals("abcd")) does if at all name were to be null.
This is usually done to prevent accidental assignment instead of comparison:
( a = null ) //will not give error
( null = a ) //will give error
I'm fairly sure efficiency is not a reason, and if it were, an optimizer would render the code the same in binary.
No, there is no difference what so ever.
not really, not in java now anyways. in older days, may be C, you could accidentally forget the exclamation mark and the code would compile fine. basically, a = null would be taken as an expression that assigned null to a and always evaluate to true (because assignment was successful).
Today's compilers are far more robust. Although, old habits die hard and I still write null != a :-)
Related
I have 2 java statements:
if(myvar!=null)
if(null!=myvar)
Some people says that second form is better because it helps to avoid NPEs, is it true? What is generally beter to use in java?
if(myvar!=null)
if(null!=myvar)
Some people says that second form is better because it helps to avoid
NPEs, is it true?
No. These are exactly the same, and there is no risk of NPE here to avoid.
Maybe you confused the example with this situation:
if (myvar.equals("something"))
if ("something".equals(myvar))
Here, if myvar is null, the first form would throw an NPE, since .equals would be dereferencing a null value, but the second one works just fine, as the .equals implementation of String handles a null parameter gracefully, returning false in this example. For this reason, in this example, the 2nd form is generally recommended.
A related argument, which one of these is preferred?
if (myvar == null)
if (null == myvar)
Consider the possibility of a typo, writing a single = instead of ==:
if (myvar = null)
if (null = myvar)
If myvar is a Boolean, then the first form will compile, the second form will not. So it may seem that the second form is safer. However, for any other variable type, neither form will compile. And even in the case of a Boolean, the damage is very limited, because regardless of the value of myvar, the program will always crash with an NPE when the if statement is reached, due to unboxing a null value.
Since no test will ever get past this statement, and since you should not release untested code, making such mistake is unrealistic.
In short, the safety benefit is so marginally small that it's practically non-existent, so I don't see a reason to prefer this unusual writing style.
Update
As #Nitek pointed out in a comment, an advantage of adopting the second form could be if you make it a habit, so that when you program in other languages where myvar = null might compile, you'd be slightly safer, out of your "good habits".
I'd still point out that in many languages comparisons with null are special, with no possibility of such typo errors. For example in Python, myvar == None is incorrect, and should be written as myvar is None, so there's no more == to mistype.
Strictly speaking, although the null = myvar writing style will not protect you in all languages, it might protect you in some, so I'd have to admit it seems to be a good habit.
This is not true, they are the same.
I prefer the first one because i think it reads better.
if(myvar!=null)
if myvar is not equal to null
and
if(null!=myvar)
if null is not equal to myvar
There is no certain difference in both of them both refer to the same check
if(myvar!=null)
if(null!=myvar)
both are the exact same things.
But in depper context it is the Yoda Condition.
It is generally criticized because of its readability issues, so try to make every thing simple for yourself and for other people who might read your code as this is not a standard notation.
This is primary opinion based, but I always go with
if (variable == null)
if (variable != null)
because imo it´s a better programming style.
And a short answer to your post, no difference between them.
There is no practical difference in your case.
15.21. Equality Operators
The equality operators are commutative if the operand expressions have no side effects.
That is, you can have a situation where the LHS and RHS matter because evaluating them can cause a change in the other, but not if one of them is the keyword null.
Consider the following example:
public class Example {
static int x = 0;
public static void main(String[] args) {
System.out.println(doit() == x); // false
System.out.println(x == doit()); // true
}
static int doit() {
x++;
return 0;
}
}
Furthermore,
15.21.3. Reference Equality Operators == and !=
The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.
shows that there is no difference in the evaluation.
As Nitek wrote in the comment to my initial question:
The second one prevents typos like "myvar=null" because "null=myvar" won't compile. Might save you some trouble.
So, we have a BIG advantage of the second form - it helps to prevent serious logic error. Example:
Boolean i=false;
....
if(null=i){
}
won't compile
but
Boolean i=false;
....
if(i=null){
}
will
But the second form has a big disadvantage - it's reading difficulties.
So I would say that in 99% cases the first form is ok, but I prefer to use the second form. If you are sure you won't mix == and = up, use the first form. If not, use the second. I'm sure there are a couple of other cases when the second form is preferred, but can't remind it at the moment.
I came across these two ways of having a null check for a string object.
Given a string object String str = "example";
If(str.someMethod() != null ) or
If (null != str.someMethod())
Why do we prefer the 2nd one ?
What is the exact reason behind this, is it related to performance ?
In your example, it makes absolutely no difference which you do (other than style), because the reason for Yoda checks is to avoid accidentally doing an assignment (but keep reading for why this doesn't matter in Java), and you can't assign to the result of calling a method.
One of the nice things about Java is that even if you were testing str, e.g.:
if (str == null)
vs.
if (null == str)
there would still be no difference, whereas in some of the languages with syntax derived from B (such as C, C++, D, JavaScript, etc.), people do the second (a "Yoda test") to minimize the odds of this bug:
if (str = null) // Not an issue in Java
In C or JavaScript, for instance, that would assign null to str, then evaluate the result, coerce it to boolean, and not branch. But in Java, that's a syntax error the compiler tells you about.
Java doesn't do that kind of boolean conversion, so the only reason for using Yoda checks in Java is if you're testing booleans, e.c.
boolean flag;
// ...
if (flag == false)
There, you might conceivably do this by accident:
if (flag = false)
But since using == and != with booleans is completely unnecessary (you'd just use if (flag) or if (!flag)), in the real world you don't need Yoda checks with Java at all.
That doesn't mean people don't still use them, as a matter of their own personal style. There's just no objective reason to, in Java.
It makes no difference performance-wise, however the Yoda programming pattern have some advantages when it comes to the world of programming skills.
In your example it would not matter as both cases would throw a NullPointerException (since you're invoking someMethod` of a null instance reference).
However, say that you wanted to check if str is null. In the first case, you'd write if (str == null) and in the second if (null == str). Both are the same. Now say that you have accidently used = instead of ==. In Java, it would not matter as the compiler wouldn't let you as the expression doesn't evalute to a boolean value. But other languages let you do that, more specifically languages that are compiler-free and only use an interperter. In that case, if you write if (str = null) you'll be assigning null to string and overriding its' current value, which would result in buggy behavior and you chasing after your tail for quite some time. However, if you'd write if (null = str) you'll get an error saying you cannot assign a value to null and thus save yourself a lot of time and effort. Again, this is not relevant to JAVA.
An example which might be relevant for Java, is the use of method invocation on constant values. For example, if (str.equals("constantString"). If str is null you'll get a NullPointerException. However, if you use a Yoad pattern and write if ("constantString".equals(str)) you'll get false as ConstantString does not equal null. This of course is only relevant for comparison, and not say contains etc.
We were having this discussion wiht my colleagues about Inner assignments such as:
return result = myObject.doSomething();
or
if ( null == (point = field.getPoint()) )
Are these acceptable or should they be replaced by the following and why?
int result = myObject.doSomething();
return result;
or
Point point = field.getPoint();
if ( null == point)
The inner assignment is harder to read and easier to miss. In a complex condition it can even be missed, and can cause error.
Eg. this will be a hard to find error, if the condition evaluation prevent to assign a value to the variable:
if (i == 2 && null == (point = field.getPoint())) ...
If i == 2 is false, the point variable will not have value later on.
if ( null == (point = field.getPoint()) )
Pros:
One less line of code
Cons:
Less readable.
Doesn't restrict point's scope to the statement and its code block.
Doesn't offer any performance improvements as far as I am aware
Might not always be executed (when there is a condition preceding it that evaluates to false.
Cons outweigh pros 4 / 1 so I would avoid it.
This is mainly concerned with readablity of the code. Avoid inner assignments to make your code readable as you will not get any improvements with inner assignments
Functionally Not Necessarily.
For Readability Definitely Yes
They should be avoided. Reducing the number of identifiers/operations per line will increase readability and improve internal code quality. Here's an interesting study on the topic: http://dl.acm.org/citation.cfm?id=1390647
So bottom line, splitting up
return result = myObject.doSomething();
into
result = myObject.doSomething();
return result;
will make it easier for others to understand and work with your code. At the same time, it wouldn't be the end of the world if there were a couple inner assignments sprinkled throughout your code base, so long as they're easily understandable within their context.
Well, the first one is not exactly inner assignment but in second case...it reduces readability ...but in some cases like below,
while ( null == (point = field.getPoint()) );
it's good to write it this way
In both cases the first form is harder to read, and will make you want to change it whenever you want to inspect the value in a debugger. I don't know how often I've cursed "concise" code when step-debugging.
There are a very few cases where inner assignments reduce program complexity, for example in if (x != null && y != null && ((c = f(x, y)) > 0) {...} and you really only need the assignment in the case when it is executed in the complex condition.
But in most cases inner assignments reduce readability and they easily can be missed.
I think inner assignments are a relict to the first versions of the C programming language in the seventies, when the compilers didn't do any optimizations, and the work to optimize the code was left to the programmers. In that time inner assignments were faster, because it was not necessary to read the value again from the variable, but today with fast computers and optimizing compilers this point doesn't count any more. Nevertheless some C programmers were used to them. I think Sun introduced inner assignments to Java only because they wanted to be similar to C and make it easy for C programmers to change to Java.
Always work and aim for code readability not writeability. The same goes for stuff like a > b ? x : y;
There are probably many developers out there not having issues reading your first code snipet but most of them are used to the second snipet.
The more verbose form also makes it easier to follow in a Debugger such as Eclipse. I often split up single line assignments so the intermediate values are more easily visible.
Although not directly requested by OP a similar case is function calls as method arguments may save lines but are harder to debug:
myFunction(funcA(), funcB());
does not show the return types and is harder to step through. It's also more error-prone if the two values are of the same type.
I don't find any harm in using inner assignments. It saves few lines of code (though im sure it doesn't improve compiling or execution time or memory). The only drawback is that to someone else it might appear cumbersome.
Hi
In our company they follow a strict rule of comparing with null values. When I code
if(variable!=null) in code review I get comments on this to change it to if(null!=variable). Is there any performance hit for the above code?
If anybody explains highly appreciated.
Thanks in advance
I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write
if (5 == variable)
rather than
if (variable == 5)
because if you forget one of the eaqual sign, you end up with
if (variable = 5)
which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.
One good advice, though, is to write
if (CONSTANT.equals(myString))
rather than
if (myString.equals(CONSTANT))
because it helps avoiding NullPointerExceptions.
My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability.
No performance difference - the reason is that if you get used to writing (null == somevar) instead of (somevar == null), then you'll never accidentally use a single equals sign instead of two, because the compiler won't allow it, where it will allow (somevar = null). They're just extending this to != to keep it consistent.
I personally prefer (somevar == null) myself, but I see where they're coming from.
It's a "left-over" from old C-coding standards.
the expression if (var = null) would compile without problems. But it would actually assign the value null to the variable thus doing something completely different. This was the source for very annoying bugs in C programs.
In Java that expression does not compile and thus it's more a tradition than anything else. It doesn't erver any purpose (other than coding style preferences)
This has nothing to do with performance. It's used to prevent that you assign accidentally instead of comparing. An assignment null = var won't make any sense. But in Java var = null also won't compile so the rule of turning them around doesn't make sense anymore and only makes the code less readable.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What's the comparison difference?
Null check in Java
Most of the developers have the habit of writing the null checking with null in the left hand side.like,
if(null == someVariable)
Does this help any way? According to me this is affecting the readability of the code.
No, it has no purpose whatsoever in Java.
In C and some of its related languages, it was sometimes used to avoid making this mistake:
if (someVariable = null)
Note the = rather than ==, the author has inadvertently assigned null to someVariable rather than checking for null. But that will result in a compiler error in Java.
Even in C, any modern compiler will have an option to treat the if (someVariable = null) as a warning (or even an error).
Stylistically, I agree with you — I wouldn't say "if 21 you are, I will serve you a drink" (unless I'd already had a couple several and was doing my Yoda impersonation). Mind you, that's English; for all I know it would make perfect sense in other languages, in which case it would be perfectly reasonable style for speakers of those languages.
It used to help in 'the olden days' when C compilers would not complain about missing an =, when wanting ==:
// OOps forgot an equals, and got assignment
if (someVariable = null)
{
}
Any modern C#/Java/C++/C compiler should raise a warning (and hopefully an error).
Personally, I find
if (someVariable == null)
{
}
more readable than starting with the null.
In your case, I don't see any merit in doing that way. But I prefer the following...
if("a string".equals(strVariable))
{
}
over this..
if(strVariable != null && strVariable.equals("a string"))
{
}