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.
Related
I was wondring what the best way to check if we have a valid reference in java. I know that this syntax works, but its a mouth full.
if (myObj == null) {
// Do something knowing we have an object
}
I'm coming from some other languages that allow you to just check a pointer like in c++.
char* prt = null;
if (ptr) {
// We know we have a valid c-string
}
Is there any equivocate or similar syntax in java? I would be okay using compiler extensions or a preprocessor.
Follow up before. Before some one jumps in a starts talking about why I should just use the java syntax because you can forget an = sign please don't.
if (myObj = null)
Will be caught by the compiler/linter.
Alas Java does not have an implicit conversion of the analogue of a nullptr_t or a pointer type to bool, so you have to use the somewhat more long-winded notation
if (myObj == null)
whereas in C++ we can write
if (myObj)
In this respect, Java is less terse, and arguably clearer.
There is no shortcut syntax for dealing with null checks in Java, not even a null coalesce or null propagation operators available in other languages. There are no user-defined conversion operators either, so you wouldn't be able to use the C++ idiom that lets you write loops on expressions returning objects, e.g. while (cin >> x) { ... }.
However, a powerful alternative exists in Java 8 to avoid null checks altogether: wrap your nullable objects in Optional<T>, and use its methods to hide null checks.
Here is a short example:
String s = "Hello";
Optional<String> os = Optional.ofNullable(s);
os.ifPresent(x -> { System.out.println(x); });
The above prints "Hello". If you set s to null, the code would print nothing.
Oracle's article on using Optional<T>.
if(x == null) {
doSomething();
}
... is the general idiom in Java. Java's designers made the decision not to allow treating non-boolean variables as implicit "truthy" values.
Another common idiom is to use x == null in a ternary statement:
return x == null ? "not found" : x;
Or to use a standard method to throw an exception early on nulls:
Objects.requireNonNull(x);
More generally, try to adopt a programming style in which you never expect null to be passed, and therefore don't have to code for the possibility.
On non-public APIs, since you never pass a null, you never need to test for null (if a NullPointerException occurs, whoever passed the null can take responsibility for the mess themselves).
In public APIs, it may be a courtesy to the caller to validate non-nulls at the point they are passed, but it's by no means essential in every case.
A reasonable goal is to always expect inputs to be non-null, and to never return a null (since Java 8, use Optional instead if necessary, or adopt the Null Object Pattern).
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.
This question already has answers here:
Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
(9 answers)
Closed 9 years ago.
This may just be a style question, but I'm reading a Java coding book ('Programming Android') and the writer all declares null first before a variable method, a practice I am not familiar with. For example:
if (null == foo) {
//code here
}
or
if (null != foo) {
//code here
}
instead of
if (foo == null) {
//code here
}
I can't see how the order would make a difference semantically/syntactically, or am I wrong here? Really just curious.
It's probably a habit left over from C/C++. In C, you would put constants on the left, because if you mistyped = instead of == there would be an error because you can't assign something to a constant. In Java, this is unnecessary because if (foo = null) also gives an error, which says that an object reference isn't a boolean.
This is a holdover from C/C++. It was advantages to put the value on the left of the == operator in case you accidently used the assignment = operator. The C compiler will catch the 14 = var as an error, but var = 14 will compile, when you meant to type var == 14. There is not much reason to do this in Java, but some still do it.
Sometimes order saves you from null pointer exception e.g. if a String variable is coming from somewhere and you compare it like this:
if(foo.equals("foo")){
}
then you might get Null pointer exception. On the other hand if you do it like this:
if("foo".equals(foo)){
}
then you not only achieve your purpose but you also avoid a null pointer exception in case String foo was null.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error..
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read
codes Left-To-Right.
Second form is better for code writer, because in java = operator is
for assignment and == operator is for test equivalent, but people
usually using in if statement = instead of ==, by second approch
developer getting Compile-Time-Error because null can't use in
Left-Side of a assignment statement.
ADDED
if (object = null) {
The convention of putting the constant on the left side of == isn't
really useful in Java since Java requires that the expression in an if
evaluate to a boolean value, so unless the constant is a boolean,
you'd get a compilation error either way you put the arguments. (and
if it is a boolean, you shouldn't be using == anyway...)
There is no difference, and
if (foo == null)
enter code here
is the prefered way; however in C, you would put constants to the left since there would be an error if you used = instead of ==
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 :-)
In a project I've been trying to familiarise myself with, I ran across a method that looks like this:
public boolean testString(String string){
return string != null && !"".equals(string);
}
What is the value of testing the string for emptiness this way instead of with the variable first? I understand why we see constant-first (Yoda syntax) in C, but is there any reason to do so with method calls in Java?
note: I do understand about NullPointerException, which is not possible in this instance. I'm looking for a value to doing it this way in this case particularly.
In this context it makes little difference, as it already tested for null. Usually you do it this way to make sure you don't call a member on a null-reference (resulting in a NullPointerException), i.e.
"test".equals(myString)
will never throw a null pointer exception whereas
myString.equals("test")
will if myString is null. So basically, the first test makes sure it's a string (not null) AND it's equal to "test".
For two strings it doesn't matter much, but when there is a non-final type involved it can be a micro-optimization.
If the left hand side is a non-overridden concrete type, then the dispatch becomes static.
Consider what the JIT has to do for
Object o;
String s;
o.equals(s)
vs
s.equals(o)
In the first, the JIT has to find the actual equals method used, whereas in the second, it knows that it can only by String.equals.
I adopted the habit of doing
"constant value" == variableName
in other languages, since it means that the code will fail to parse if I mis-type = instead of ==.
And when I learned Java, I kept that order preference.
The usual reason for using "constant string".equals(variable) is that this works properly even if variable is null (unlike variable.equals("constant string")). In your case, however, since you are testing that string != null in a short-circuit boolean test, it's entirely a matter of style (or habit).
If they just did this:
!"".equals(string);
then they're avoiding the possibility of a NullPointerException, which is pretty smart. However, they're checking for null right before this condition, which is technically not necessary.
Is it running any tools like checkstyle? if it is, putting the variable first will result in checkstyle failing. Another reason is that if you put the empty string first it will take away the possibility of getting a null exception if the variable is null because the expression will always evaluate to false. If you had the variable first and the variable was null it will throw an exception.
It is more than a coder preference. If the purpose of the method was only to check that string is not an empty String (without caring whether its a null) then it makes sense to have the constant first to avoid a NullPointerException.
e.g. This method will return the boolean outcome. false in case string is null.
public boolean testString(String string){
return !"".equals(string);
}
while this one may throw a runtime exception if string is null
public boolean testString(String string){
return !string.equals("");
}
No, it is unnatural, and harder to read. It triggers a pause for most readers, and may wastefully consume lots of resources on stackoverlow.com.
(Better use string.isEmtpy() anyway)
There are no fixed rules tho, sometime this is easier to read
if( null != foobar(blahblahblah, blahblahblah, blahblahblah) )
than
if( foobar(blahblahblah, blahblahblah, blahblahblah) != null )
This question can be answered on a number of levels:
What does the example mean?
As other answers have explained, !"".equals(str) tests if str is an non-empty string. In general, the <stringLiteral>.equals(str) idiom is a neat way of testing a string that deals with the null case without an explicit test. (If str is null then the expression evaluates to false.
Is this particular example best practice?
In general no. The !"".equals(str) part deals with the case where str is null, so the preceding null test is redundant.
However, if str was null in the vast majority of cases, this usage would possibly be faster.
What is a better way to do this from a code-style perspective?
return "".equals(str);
or
return str != null && !str.isEmpty();
However, the second approach doesn't work with Java versions prior to 1.6 ... because isEmpty() is a recent API extension.
What is the optimal way to do this?
My gut feeling is that return str != null && !str.isEmpty(); will be fastest. The String.isEmpty() method is implemented as a one-line test, and is small enough that the JIT compiler will inline it. The String.equals(Object) method is a lot more complicated, and too big to be inlined.
Miško Hevery (see his videos on youtube) calls this type of overkill "paranoid programming" :-)
Probably in this video:
http://www.youtube.com/watch?v=wEhu57pih5w
See also here: http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/