A NullPointerException
is thrown when a method is called on an object that is null.
Errors contain the line number on which an exception is thrown at runtime.
Let’s see an example to reproduce the NullPointerException
before Java 14 version.
package java14;
public class JavaNullTest {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp.department.name);
}
}
class Employee {
Department department;
String name;
}
class Department {
String name;
}
Outputs:
Exception in thread "main" java.lang.NullPointerException
at HelloWorld.main(HelloWorld.java:7)
The above error is same for accessing property and method, assigning property on null object.
java14 NullPointerException enhancement
In Java14
, It improves the error message display to an user.
It gives an following error while accessing the property on null object.
- reading property on null object
emp.department.name throws below error as department is null. here you are reading the property on Null object. Exception in thread “main” java.lang.NullPointerException: Cannot read field “name” because “emp.department” is null at java14.JavaNullTest.main(JavaNullTest.java:6)
- calling method on Null Object
let’s see an example to call method on null object
calling emp.department.getName() method, throws below error. Exception in thread “main” java.lang.NullPointerException: Cannot invoke “java14.Department.getName()” because “emp.department” is null at java14.Java14NullTest.main(Java14NullTest.java:6) Here department is null, and calling getName() method throws this error. department
package java14;
public class Java14NullTest {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp.department.getName());
}
}
class Employee {
Department department;
String name;
}class Department {
String name;
String getName(){
return name;
}
}
- Assign value to null object property
In this example, You are assigning string to an property of an null object and throws below error Exception in thread “main” java.lang.NullPointerException: Cannot assign field “name” because “emp.department” is null at java14.Java14NullTest.main(Java14NullTest.java:6)
here is an example
package java14;
public class Java14NullTest {
public static void main(String[] args) {
Employee emp = new Employee();
emp.department.name="john";
}
}
class Employee {
Department department;
String name;
}class Department {
String name;
String getName(){
return name;
}
}
This features is not enabled by default, You have to pass command line options -XX:+ShowCodeDetailsInExceptionMessages
to display this type of errors at runtime.