Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Null Reference Best Practice

In java, Which of the following is the more "accepted" way of dealing with possibly null references? note that a null reference does not always indicate an error...

if (reference == null) {
    //create new reference or whatever
}
else {
    //do stuff here
}

or

try {
    //do stuff here
}
catch (NullPointerException e) {
    //create new reference or whatever
}
like image 547
Woodrow Douglass Avatar asked May 13 '11 12:05

Woodrow Douglass


People also ask

How do you handle null reference in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Can reference be null in Java?

In Java programming, null can be assigned to any variable of a reference type (that is, a non-primitive type) to indicate that the variable does not refer to any object or array.

Why is checking for null a good practice?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

Can we throw NullPointerException Java?

You can also throw a NullPointerException in Java using the throw keyword.


1 Answers

Catching exceptions is relatively expensive. It's usually better to detect the condition rather than react to it.

like image 68
Paul Tomblin Avatar answered Oct 07 '22 14:10

Paul Tomblin