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.
Related
I have a graph related method which returns the neighboring nodes of a certain node.
If the one node has no neighbors it returns null, the method is the following
public Iterable<Node> getNeighbors(Node v) {
if (!this.adjacencyList.get(v).isEmpty())
return this.adjacencyList.get(v);
return null;
}
I try to avoid the exception using the following :
if (graph.getNeighbors(nodeIterator.name) == null)
nodeIterator = all_graph_nodes.iterator().next();
Iterable<Node> adjNodes = graph.getNeighbors(nodeIterator.name);
The NullPointerException is raised even using the previous code.
How to solve this ?
If you're still getting an NPE, then the problem is in getNeighbours and not the second snippet.
this.adjacencyList is null, -OR-
this.adjacencyList.get(v) returns null.
Given that you're passing a name to a method that will then do a lookup by node, and that you can't call .get(someNodeRef) on a list, adjacencyList is probably some sort of hashmap, so your names are off and you should rename some things. Map's .get(x) method returns null if an entry is not found, so most likely the culprit is that v isn't in the map at all, and thus .get(v).isEmpty() throws NPE.
The fixes are as follows:
You should NEVER return null when a valid sentinel value that carries the intended semantic meaning is available. A mouthful, but it means here: Why are you returning null when you intend to treat that the exact same way as 'zero nodes'? There is an instance of Iterable<Node> that properly represents the concept of zero nodes, and it isn't null. It's List.of() or equivalent: An empty list has no nodes. Great. That's what you intended. So return that.
.get(v).isEmpty() is bad code here, as it would mean an NPE occurs if you ask for a non-existent node. Unless, of course, you want it to work that way. An easy way out is the defaulting mechanism: Call .getOrDefault instead:
if (!this.adjacencyList.getOrDefault(v, List.of()).isEmpty()) ....
except, of course, you should never be returning null when you can return an empty list instead, so your getNeighbours method becomes simply:
return adjacencyMap.getOrDefault(v, List.of());
that one-liner will fix all things.
In general, if you are writing code where null is dealt with in some way, and some sentinel value (such as a blank string or an empty list) is dealt with in the same way, your code is badly styled; however you got that null should have gotten you that empty value instead. e.g. if you ever write this:
if (x == null || x.isEmpty()) ...
you messed up. Figure out where you got x from. Update it there, make x the blank sentinel ("" for strings, List.of for lists, etcetera).
That, and use .getOrDefault and other such methods more: Methods that let you provide what should happen when e.g. a key is not found.
You should probably avoid returning null from your getNeighbors method. It's not good practice to return null for Iterables, Iterators and Collections, since an empty iterable would represent the same concept (there is nothing in that adjacency list) without all the dangers of null. And your code would be simpler. You can check if the iterable contains anything and if not then default to the full iterator.
You should avoid returning null at all cost. This is of high danger as it may cause Null Pointer Exceptions to be thrown during runtime. Such exceptions are horrific to debug as they usually hide implementation errors due to the place where the exception was thrown is most likely far away from the original implementation error.
Your case is actually a good example of such behavior as it is not directly understandable where the NPE is coming from.
In situations in which the appearance of a null value is inevitable (e.g. as #rzwitserloot pointed out, Java's Map get method) and there is the possibility of exposing it to client objects (e.g. your getNeighbors method may expose such null value) I like to use Java's Optional which (as stated in the docs) is:
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
This object will act as wrapper to objects which may be assigned as null thus preventing it to be used directly and possibly preventing NPEs to be thrown.
In your case this would apply as follows (note that this is assuming that adjancencyList is a non-null object and that its get method is the one actually throwing the NPE):
public Optional<Iterable<Node>> getNeighbors(Node v) {
return Optional.ofNullable(this.adjacencyList.get(v));
}
if (!graph.getNeighbors(nodeIterator.name).isPresent()) {
nodeIterator = all_graph_nodes.iterator().next();
}
Iterable<Node> adjNodes = graph.getNeighbors(nodeIterator.name).get();
Note that by wrapping the original get method in an Optional object there is no longer the propagation of a raw null value hence preventing it to be used by the client. You are moving the responsibility of dealing with null to your side only and protecting clients to handle them instead.
Another great advantage of using Optional as a method's return type is that it implicitly declares that the return object of the method may or may not be present. This forces clients to understand that its return value may be empty (null) and thus force it to act accordingly.
This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 6 years ago.
I have seen in many places that the constant value is used first and then the variable for example ("ram").equals(a) and in many places I have seen that the variable is used first and then the constant value with which they want to compare for example a.equals("ram").
what is the difference between a.equals("ram") and ("ram").equals(a) ?
which one is better to use and why ?
The first style is safer in situations when variable a is allowed to be null, because you can skip null checking.
When you write
if (a.equals("ram")) { ... }
you must ensure that a is not null to avoid a null pointer exception. This is not necessary for
if ("ram".equals(a)) { ... }
because equals() method is required to process null arguments without throwing an exception:
For any non-null reference value x, x.equals(null) should return false.
("ram").equals(a) is better. The code will never break even if a is null.
saves us from null pointer exception.
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?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is null in Java?
How is null implemented in Java?
Suppose I say
String x = null;
How is this null stored internally?
Check out this question:
What is null in Java?
Basically, usually stored as 0's same as C++ but this can be implementation-specific and so you shouldn't rely on it.
As per java specification it is a sort of literal.
There is also a special null type, the type of the expression null,
which has no name. Because the null type has no name, it is impossible
to declare a variable of the null type or to cast to the null type.
The null reference is the only possible value of an expression of null
type. The null reference can always be cast to any reference type. In
practice, the programmer can ignore the null type and just pretend
that null is merely a special literal that can be of any reference
type.
In Java the runtime must ensure that all heap-allocated memory is zeroed out before the pointer to the block is exposed to the Java code. The all-zeroes block will be interpreted as the initial values of the instance fields. This pretty much guarantees that null will be implemented as a zero value in any JVM implementation.
The null value is stored in the variable x.
I find stuff like this rather annoying and ugly in equals methods:
if (field == null)
{
if (other.field != null)
return false;
}
else if ( ! field.equals(other.field))
return false;
In C# I could've done this:
if( ! Object.Equals(field, other.field))
return false;
Is there something similar in Java, or what is the preferred way to do this kind if thing?
Java 7 offers java.util.Objects.equals.
Use commons-lang:
org.apache.commons.lang.ObjectUtils.equals(Object object1, Object object2)
Source code:
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if ((object1 == null) || (object2 == null)) {
return false;
}
return object1.equals(object2);
}
From Apache
http://commons.apache.org/lang/
That's about equivalent to what you do in C#
Guava equal which does this :
public static boolean equal(#Nullable Object a, #Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
or null object pattern
Guava also has the somewhat related comparison chain and a load of other goodies.
I would write it this way:
return field != null && other.field != null && field.equals(other.field);
which is not as elegant as the C# code line, but much shorter then the if tree you posted.
I accept all answers technically. Practically I will not use any of them in code I have under control because all provided solutions are working around the core problem: null-values. KEEP YOUR CORE MODEL FREE FROM NULL VALUES, and the question is obsolete in this case.
At system borders like third party libraries one has to deal with null values sometimes. They should converted into meaningful values for the core model. There the given solutions are helpful.
Even if Oracle recommends the equals-Methods to be null-safe, think about that: Once you accept null values your model it is getting fragile. The equals-method will not be the last method where you will check for null. You have to manage null-checks in your method call hierarchy. Methods may not be reusable out of the box anymore. Soon, every parameter will be checked for null.
I saw both sides:
On one side code full of null checks, methods that trust not a single parameter anymore and developers that are afraid to forget a null check.
On the other side code with full expressive statements that make clear assertions to have full functioning objects that can be used without fear of NullPointerExceptions.
As part of the Project Coin, there was a proposal for adding a series of null-safe operators to Java. Sadly, they didn't make it into Java 7, maybe they'll appear in Java 8. Here is the general idea of how they would work
Actually everyone follows there own way to do this and also i would like to introduce groovy here.
There is one way
field == null ? false : true; // So basically it will return true when it is not null.
In groovy there is null safe operator for objects. Lets take an example for class
A {
String name = "test1"
String surName = "test2"
public String returnName() {
return name + surName
}
}
A a = null
a?.name
// Mentioned operator ? will actually check whether a is null or not. then it will invoke name.
Note: i didn't applied semi colon in code as this is not require in groovy.
String.valueOf() will solve some of those problems if the toString is implemented for your classes. It will spit out the toString() answer or "null" if the pointer is null.
Use == operator when you are checking for object references, if both the references refers same object it will return true. Otherwise if you are looking for object content then go with .equals method of objects.
So null means it doesn't have any memory location given in heap. So it can be simply checked with '==' operator.