how null is checked in java?
This question already has an answer here:
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
}
}
链接地址: http://www.djcxy.com/p/76158.html
下一篇: 在java中如何检查null?