Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
NullPointerException
Java Exceptions Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Exceptions Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java exceptions.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Let's move on to another common error many programmers have experienced first-hand, the "NullPointerException". Remember that a null value can be assigned to any object reference including strings. The NullPointerException is thrown when the program tries to use an object reference that has the null value. Take a look below to see an example.
NullPointerExample.java
package exlcode;
public class NullPointerExample {
public static void main(String[] args) {
try {
// NullPointerException will be thrown because
// exampleVariableOne is being compared to a null value
Double exampleVariableOne = new Double(Math.PI);
Double exampleVariableTwo = null;
exampleVariableOne.compareTo(exampleVariableTwo);
System.out.println("None of the objects are null");
} catch (NullPointerException e) {
System.out.println("exampleVariableOne cannot be compared to a null value");
}
}
}
The "NullPointerException" is thrown when we compare an object to a null value. As an exercise, change the value above to stop the exception from being thrown.
Working with null values may not be the best practice because there may be situations where the "NullPointerException" is thrown by the program. The most effective way to avoid a "NullPointerException" is to check all object references before accessing one of the object's fields or methods. Use the try{} and catch{} blocks to check if the object is null.