I want to check for a null pointer when accessing a field several classes deep (in a chain of get methods). However, if one of the earlier methods is null I get a NullPointerException anyways.
This is what I want to check, though it can still get a NullPointerException:
if(x.getLocation().getBuilding().getSolidFuelInd() != null)
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
This the behavior I want the above code to exhibit:
if(x.getLocation() != null)
if(x.getLocation().getBuilding() != null)
if(x.getLocation().getBuilding().getSolidFuelInd() != null)
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
The field on the pol is optional and should only be set if the above getter is not null. However the building and location objects could also be null, so now I must check to that they're valid.
Is there any sort of shorter way to check all the above like I want?
With Java 8's Optional<> class, you can map a value as so:
Optional.of(x)
.map(ClassOfX::getLocation)
.map(Location::getBuilding)
.map(Building::getSolidFuelInd)
.map(solidFuelInd -> solidFuelInd ? "Y" : "N")
.ifPresent(pol::setWood_heat_ind);
map calls will only be executed if the value of the optional isn't null thus avoiding the NullPointerException.
ifPresent's purpose is to call your setWood_heat_ind only if a value if available.
A nice single-call equivalent to null checks.
If its code reduction you want then you can save each call in a variable.
// note: Replace type with the correct type
type location = x.getLocation();
type building = location == null ? null : location.getBuilding();
// note: you don't have to check for null on primitive types
pol.setWood_heat_ind(building != null && building.getSolidFuelInd() ? "Y" : "N");
This is much cleaner and easier to follow.
Food for thought, you don't check for null on primitive types boolean, int, byte etc. so the last null check on building.getSolidFuelInd() is not needed
Java 8 has Optional<T> which would make for one chained expression, though verbose.
However Java 8 also has Stream<T> and you could have a
"stream" of 0 or 1 item, and then query with lambdas.
x.getLocation()
.map((loc) -> loc.getBuilding())
.map((building) -> building.getSolidFuelInd() != null)
.findFirst()
.ifPresent ...
Or
x.getLocation()
.map(Location::getBuilding)
.map(Building::getSolidFuelInd())
.filter(fuelInd -> fuelId != null)
.findFirst()
.ifPresent ...
It probably will be a matter of slow coming to terms with an application of those new terms.
You could just catch the exception
try{
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
}catch(NullPointerException e){
//e.printStackTrace(); or whatever you want
}
(Referring to your possible solution) checking for the returned values implies invoking the same methods more the once, that's why I would use this solution.
As Jay Harris pointed out, you can obviously check the values and save the return parameter, without having to invoke the same method again. You can do it in many different ways, here one
Object loc=null,build=null;
Boolean SFI = ((loc=x.getLocation())==null?null:
((build=loc.getBuilding())==null?null:
(build.getSolidFuelInd())));
if(SFI!=null)pol.setWood_heat_ind(SFI?"Y":"N");
But is it worth it? I made this more complicated than it could on purpose, but anyway, why doing that if you can try...catch in two simple lines?
Related
We have all seen that kind of code
if (myObject!= null
&& myObject.mySubObject() != null
&& myObject.mySubObject().getSpecificValue() != null
&& !myObject.mySubObject().getSpecificValue().isEmpty()
) {
......
}
How could I write this the clean way ?
You can do chaining with Optional:
Optional.ofNullable(myObject)
.map(o -> o.mySubObject())
.map(so -> so.getSpecificValue())
.map(sv -> sv.isEmpty())
.orElse(false)
Or with method references even shorter (does the same):
Optional.ofNullable(myObject)
.map(Foo::mySubObject)
.map(Bar::getSpecificValue)
.map(Baz::isEmpty)
.orElse(false)
where Foo, Bar and Baz are the names of the respective classes.
If you are using someone else's code then you're really stuck handling for a possible null. On the other hand, if you have control over the code base then never return a null object, and make that a rule across your entire application.
This may sound bad at first but I have developed several enterprise-level applications and this is a very effective way to make the code consistent and much more readable.
So, now, this
if (myString != null && !myString.isEmpty()) {
becomes simply
if (!myString.isEmpty()) {
In lue of that option use the new Optional feature in J8 as it is intended for that purpose.
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.
This question already has answers here:
Java Object Null Check for method
(8 answers)
Closed 7 years ago.
I was working on some project and got a condition when I have to check the object is null or not from a list and all variables of the object are null.
So can someone explain to me how an object is checked for null i.e. variable wise or some other way.
how an object is checked for null internally in java don't want the code. want the concept
Please in a little detail.
My Question: How Java internally checks if object contains a null value?
Apparently, you are actually asking how null checks are implemented under the hood.
The answer is implementation specific. It could be different for different JVMs and / or execution platforms. (If you want to research the specific implementation on a specific JVM, I suggest you checkout the JVM source code and/or get the JIT compiler to dump out the compiled native code for you to examine.)
Basically, there are two approaches:
An explicit x == null test will typically compile to an instruction sequence that compares the value of x against the value that represents a null. That is usually a 32-bit or 64-bit zero.
The implicit null check in x.toString() could be done the same way. Alternatively, it could be done by simply treating x as a machine address and attempting to fetch a value at that address. Assuming that the zero page has not been mapped, this will trigger a hardware "segmentation fault" exception. Java uses native code mechanisms to trap that exception, and turn it into a NullPointerException.
If you're looking at a single item:
if(object == null)
{
(...)
}
You mentioned a list. Let's pretend it's an ArrayList of Objects:
for(Object o : array_list)
{
if(o == null)
{
(...)
}
}
You'd also want to check to see if your list is null before you start looping through it.
Basically any can be easily checked for null value. Every internal details and implementations of null and comparison with object are totally managed by java so all we need is to have a compare of the object with null as :-
Object obj = null; // Object can be replaced with any class
if(obj == null){
// do your logics
}
As far as any List or Collection is considered, to see if object stored in it are null or not :-
List <String> list = new ArrayList<String>();
list.add("hi");
list.add(null);
for(String s : list){
if(s == null){
// do your logics here
}
}
Java does not check if an object is a "null".
You cannot have a null object as null does not extend the Object class.
What you can do in java is have a variable assigned to null, meaning it references "nothing". (In reality, it is referencing the bytes that null is defined as)
That is what the other answers are doing, they are checking if a reference variable is actually pointing to nothing (null). An object itself, however, is never null.
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.