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.
Related
If I try to do a .equals() on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to some constant string, can I do the following:
MY_CONSTANT_STRING.equals(aStringVariable)
I know it will work, but is this just really poor code?
This is a standard Java idiom jokingly called a Yoda condition.
Personally I prefer to handle the null case explicitly, but the Yoda way is used a lot and any experienced Java programmer should be able to understand what is going on immediately. It's fine to use.
is this just really poor code?
No, this is the way many people would code the statement to avoid NPE.
What you've got is fine. It's even possible to use a String literal.
if( "value".equals(variable) ) {
...
If you don't like that, you can always explicitly check for null and equality, and combine the two checks with &&. The short circuiting of the operator will make sure you never get a NPE.
if( (variable != null) && variable.equals("value") ) {
...
I would keep the "CONSTANT.equals(possibleNull)" code without the null test only if it is a normal condition that the variable could be null - for instance because it just came out of a property map.
Similarly you can get away with not checking for null in instanceof-checks - like:
Food dinner = map.get("dinner");
if (dinner instanceof Soup) {
((Soup)blah).eat();
} // We don't care if it is a Fish or null
But if you really did not expect null, you should explicitly check for that in a separate if-test, and handle it appropriately. It's generally better to catch such data errors early rather than later.
Nope, it's usually done to avoid NPE. However, I usually prefer to do explicit check for null.
If you are concerned about the quality of your code, write a helper class that takes care of equality test:
public class ObjectHelper {
public static boolean testEquality(Object o1, Object o2) {
if (o1 == null && o2 == null) return true;
if (o1 == null) return false;
return o1.equals(o2);
}
}
Then use it like this:
if (ObjectHelper.testEquality(aStringVariable, My_CONSTANT_STRING))
Your so-called constant MIGHT stop being constant. It might be read from a configuration file some time in the future.
I'm doing a null pointer check and would like to know if there is any better way in java 8 other than optional feature
if (cake != null && cake.frosting != null && cake.frosting.berries != null) {
//Do something
}
I'm looking if there is any in-line null pointer check
The Elvis operator is what you would want, but it's not part of the Java language. In Groovy you would simply do cake?.frosting?.berries. As you said, you could use Optional if(Optional.ofNullable(cake).map(c -> c.getFosting()).map(f -> f.getBerries()).isPresent()) but that IMHO is quite horrible and not the intended use for Optional. Your if statement, as you wrote it, is simple and easy to read.
Maybe something like
try{
cake.frosting.berries.toString();
}catch(NullPointerException npe){
return;
}
//do something
I'm trying to know whether we can write null check pointer in the same statement in Java, as we do in groovy? I've four places to check null. Can this be more simplified?
if(doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM") != null) {
if(doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) != null) {
Node searchResultNode = doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0);
if(searchResultNode != null) {
}
}
}
as
doc.getDocumentElement()?.getElementsByTagName("SEARCH-RESULT-ITEM")?.item(0)
Is it possible
You asked if it is possible to write Groovy-like code in a regular Java project. The simple answer is no.
However, the statement can be simplified by combining the null checks into one condition. In addition, if doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) is not null we don't need to check the local variable.
So we may end up with:
if (doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM") != null
&& doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) != null {
Node searchResultNode = doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0);
}
Doing this reduces the number of IF statements from 3 to 1, and eliminates a redundant null check.
There is no safe dereference in Java.
It's generally bad practice to toss nulls around and Optional class may come to rescue as well ass checkNotNull at the beginning of the method, but nothing as fancy as Groovy one-liners.
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 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.