I saw this piece of code today and wanted to know is there a difference between
return (null==employeeName ? "": employeeName);
and
return (employeeName == null ? "": employeeName);
Not anymore.
It used to be the case, in the wild days of C and C++ that non-boolean expressions, were OK in if statements, so that there would be no difference, unless you made a classic programmer mistake and forgot an equals sign:
employee = null
would compile, but
null = employee
would not.
This doesn't matter in Java, because an Employee type isn't a boolean, and the compiler, rather than the syntax, stops you from shooting yourself in the foot; but whoever wrote that was probably in the habit from their days of writing C.
No difference. Just a different order of writing the operands. Personally I'd prefer the second one.
No difference, both are the same in terms of returning the result. But I prefer
return (employeeName == null ? "": employeeName);
both are the same, there is no difference.
This is common, and not same.
//This is safe against null employeeName:
return ("".equals(employeeName) ? "": employeeName);
return (employeeName.equals("") ? "": employeeName);
There is a classical coding standard that while doing any comparisons between constants and variables or literals and variables, the constant/literal should be on the left hand side.
So when you want to check whether status is COMPLETE, it was recommended to do it this way:
if("COMPLETE".equals(status))
{
}
The advantage here is that a null check on status was not required. doing the normal way: if(status.equals("COMPLETES")) will throw a NullPointerException if status were null.
In my opinion, this is more of a programming style. I find the normal way more readable even with an extra null check:
if(status != null && status.equals("COMPLETES"))
And a missing null check should anyway be found by a good unit test suite.
Related
This question already has answers here:
Which has better performance: test != null or null != test [duplicate]
(8 answers)
Closed 9 years ago.
I have a doubt regarding coding standard of a null check.
I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?
Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use null != a.
The null != a is an old practice in programming languages like Java,C++ (called as Yoda Conditions).
As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.
There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".
Once I was working in a project where the coding guideline was to use if (null != a) because they thought it is easier for the developer to understand that the constant value has to come first always (as in CONSTANT_VALUE.equals(variable). That was pretty annoying to me.
They're both the same. It depends on your coding style.
From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.
No difference betwwen them if statement works based on result of expression
so u write either if(a!=null) or if(null!=a) will produce true or false then result is evaluated.
So it doesnt matter you write which you like
They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null
Example "some value".equals(your_variable) , some value can be any value you know is not null. This will avoid NPE when your_variable is null.
String str = "somevalue";
if(str != null && str.equals("somevalue")) { }
if("somevalue".equals(str)) { }
Both the conditions will be same if str is null or not.
Is there a difference between null != something and something != null in Java. And if there is a difference then which one should I use and why??
There's no difference between null != something and something != null. You must be thinking about the person.getName().equals("john") and the "john".equals(person.getName()) difference: the first one will throw a NullPointerException if getName() returns null, while the second won't. But this is not applicable for the example of your question.
its probably comming from the so-called joda-conditions where you write "bla" == myVariable instead of myVariable == "bla" because it could happen to accidentially write myVariable = "bla" which returns "bla" in some languages but also assign "bla" to myVariable
I just want to point out that the "Yoda condition" rationale for doing this (in languages like C & C++) does not apply in this (Java) case.
Java does not allow general expressions to be used as statements, so both
something == null;
and
null == something;
would be compilation errors.
The types of something == null and something = null are different; boolean and some reference type respectively. In this case, it means that both:
if (something = null) {
...
}
and
if (null = something) {
...
}
would be compilation errors.
In fact, I can't think of a realistic example where null == something would be compilation error and something == null would not. Hence, it doesn't achieve anything in terms of mistake-proofing.
There is no difference, but some people use it for ease of readability in their code.
Point of view of performance there will be no difference, both sides of the operator are executed any way. But for a more readable code second one seems more readable
obj.getSomething().getAnotherThing().doSomething() != null
null != obj.getSomething().getAnotherThing().doSomething()
But if you are going to just compare a variable or parameter this is more readable
something != null
Of course this depends on sense of reader.
In java if we compare any, always we have to place variables at left hand side and values are placed at right hand side...
They are both the same there is no difference.
The following line of code is in one of my if statements:
$("#dateOfTransaction_month").val() != "${loadInstance?.payment?.dateOfTransaction?.getAt(Calendar.MONTH) + 1}"
Since Java's date/time management is such a mess I have to write + 1 to get the correct month. The problem is that sometimes a payment object might not exist, so I would basically be saying null + 1. This gives me the error Cannot invoke method plus() on null object. Is there any neat way (neat being something like Groovy's safe navigation operator) I can account for the possibility of a payment object being null in the if statement, or am I forced to check to see if the value is null before the if statement?
Groovy adds a plus() method to Date which is what the + operator calls. You can directly call this yourself and chain a safe-navigation operator to it.
$("#dateOfTransaction_month").val() != "${loadInstance?.payment?.dateOfTransaction?.getAt(Calendar.MONTH)?.plus(1)}"
http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#plus(int)
On that same page you have linked, actually right above, is the Elvis operator (some-maybe-null-value ?: default).
With the Elvis you can assign a default value you want to use.
e.g.
$("#dateOfTransaction_month").val() != "${(loadInstance?.payment?.dateOfTransaction?.getAt(Calendar.MONTH) ?: 0) + 1}"
Which would then default to being January
To solve the issue of working with the annoying Java Date and Calendar API's you might check out JodaTime. It's a dream to work with when compared to the built in API's.
That is one thing i really like about Groovy when I played around with it, the ?. operator that automatically tested for null references.
There is no such thing in Java, you just have test whatever object hierarchy your are traversing to check for null values:
if (object1 != null && obecjt1.obecjt2 != null && object1.object2.object3 != null)
do_something_awesome_with(object1.object2.object3);
However, your example is always going to cause trouble, because Groovy's ?. operator simply stops your traversal when it encounters a null reference and returns null.
Which one is recommended and to be used to check the Object null-ness?
null != Object
or
Object != null
and other way
null == Object
or
Object == null
...and is there any difference between them?
(In)equality is commutative, so there is no difference.
Historically the former stems from C to avoid accidentally assigning a value in a conditional statement, however that mostly applies to ==, not !=. Also Java requires the condition in a conditional statement to have a boolean value, so the only place where it could go wrong nowadays would be
if (a == false) ...
if you accidentally omit one of the =. A rare case, I guess (though probably not so much, given what students frequently write in their first two terms). Joonas also points out another (more obscure) case in the comments.
It's always more readable to use
Object != null
because that reads as "the object is not null", which is literally what the condition is.
The only case where you want to swap the two is to avoid accidentally using
Object = null
which will return true even though it is not the desired behavior, when you wanted to say
Object == null
but in reality not only do modern tools catch these kinds of mistakes, but wide use of the reverse can actually be an impediment to anyone who has to read the code.
I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.
Recomendation:
String variable;
"xx".equals(variable) // OK
variable.equals("xx") //Not recomended
Because prevents appearance of NullPointerException that are not controlled
Is this true?
This is a very common technique that causes the test to return false if the variable is null instead of throwing a NullPointerException. But I guess I'll be different and say that I wouldn't regard this as a recommendation that you always should follow.
I definitely think it is something that all Java programmers should be aware of as it is a common idiom.
It's also a useful technique to make code more concise (you can handle the null and not null case at the same time).
But:
It makes your code harder to read: "If blue is the sky..."
If you have just checked that your argument is not null on the previous line then it is unnecessary.
If you forgot to test for null and someone does come with a null argument that you weren't expecting it then a NullPointerException is not necessarily the worst possible outcome. Pretending everything is OK and carrying until it eventually fails later is not really a better alternative. Failing fast is good.
Personally I don't think usage of this technique should be required in all cases. I think it should be left to the programmer's judgement on a case-by-case basis. The important thing is to make sure you've handled the null case in an appropriate manner and how you do that depends on the situation. Checking correct handling of null values could be part of the testing / code review guidelines.
It is true. If variable is null in your example,
variable.equals("xx");
will throw a NPE because you can't call a method (equals) on a null object. But
"xx".equals(variable);
will just return false without error.
Actually, I think that the original recommendation is true. If you use variable.equals("xx"), then you will get a NullPointerException if variable is null. Putting the constant string on the left hand side avoids this possibility.
It's up to you whether this defense is worth the pain of what many people consider an unnatural idiom.
This is a common technique used in Java (and C#) programs. The first form avoids the null pointer exception because the .equals() method is called on the constant string "xx", which is never null. A non-null string compared to a null is false.
If you know that variable will never be null (and your program is incorrect in some other way if it is ever null), then using variable.equals("xx") is fine.
It's true that using any propertie of an object that way helps you to avoid the NPE.
But that's why we have Exceptions, to handle those kind of thing.
Maybe if you use "xx".equals(variable) you would never know if the value of variable is null or just isn't equal to "xx". IMO it's best to know that you are getting a null value in your variable, so you can reasign it, rather than just ignore it.
You are correct about the order of the check--if the variable is null, calling .equals on the string constant will prevent an NPE--but I'm not sure I consider this a good idea; Personally I call it "slop".
Slop is when you don't detect an abnormal condition but in fact create habits to personally avoid it's detection. Passing around a null as a string for an extended period of time will eventually lead to errors that may be obscure and hard to find.
Coding for slop is the opposite of "Fail fast fail hard".
Using a null as a string can occasionally make a great "Special" value, but the fact that you are trying to compare it to something indicates that your understanding of the system is incomplete (at best)--the sooner you find this fact out, the better.
On the other hand, making all variables final by default, using Generics and minimizing visibility of all objects/methods are habits that reduce slop.
If you need to check for null, I find this better readable than
if (variable != null && variable.equals("xx")). It's more a matter of personal preference.
As a side note, here is a design pattern where this code recommendation might not make any difference, since the String (i.e. Optional<String>) is never null because of the .isPresent() call from the design pattern:
Optional<String> gender = Optional.of("MALE");
if (gender.isPresent()) {
System.out.println("Value available.");
} else {
System.out.println("Value not available.");
}
gender.ifPresent(g -> System.out.println("Consumer: equals: " + g.equals("whatever")));