Exception in thread "main" java.lang.NullPointerException at NPE.main(NPE.java:5)This tells us that at line 5 in the file NPE.java, there was a NullPointerException.
objectName.fieldon that line and we have found the source of the exception.
Line 5 of NPE.java in this case is:
String str = obj.toString();Since there is only one method invocation here, we know it is the cause. The toString method of
objwas invoked. The reference
objmust be null. At this point we can work backwards to find out why obj is null, and who was supposed to set it to a valid reference.
System.out.println(obj.toString());In this case there are 3 dereferences. However, examining them quickly determines that System is the System class and should never be null, and that System.out should never be null either. So again obj is the only possible culprit.
boolean flag = object.getBooleanFlag();You are debugging and
objectis a valid reference (not null). Since that is the only dereference on the line, it looks like there can't be an NPE here. But if getBooleanFlag returns a Boolean object, Java tries to convert it to a boolean primitive. If getBooleanFlag returns null, then the conversion to the primitive value (called unboxing) fails with a NullPointerException.
Copyright © 2020 Andrew Oliver