Hello Hello - 1 year ago 85
Java Question

Handling null reference

Public Static Void Main() {
LinkedList q = new LinkedList();
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)

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

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download