Hello Hello - 4 months ago 12
Java Question

Handling null reference

Public Static Void Main() {
LinkedList q = new LinkedList();
q.enqueue(Object);
System.out.println(q.deque().getString()); //it will print the string of the popped object
}


If the queue becomes empty, it will give exception as q.deque() refers to null and any method on null will give exception.

we can achieve this by changing it to:

Object k = q.dequeue();
if(k != null)
System.out.println(k.getString());


Is there any better way to do this instead of checking null pointer in the main program?

Answer

As per java best coding practice, if you have a method returning a collection such as list/set/map and in case when the collection has no elements in it, then it is always good to retunr empty collection instead of null.

For example you can use for list:

return Collections.emptyList(); // when the list is empty instead of return null

This saves null pointer exception on the calling code if programmer has missed null pointer check.

Hope it helps!