Helpful NullPointerException messages
Static fields and methods are named in the message. Local variables need javac -g to appear by name.
An object lives as long as some chain of references from the running program can reach it; after that the garbage collector may reclaim it, at a time you don't control. null means "no object", and using it as if it were one throws NullPointerException.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Profile whose constructor requires a non-null email (with Objects.requireNonNull and a message) and allows a null nickname, with a method displayName() that returns the nickname or, if it's null, the part of the email before @. Show both cases and a rejected null email.
Write a method static int safeLength(String s) that returns 0 for null, and print it for null, "" and "java".
Create a tiny cycle: two Node objects whose next fields point at each other, print a.next.next == a, then set both local variables to null. Write in a comment whether the cycle can be collected and why.
Explain it without notes
When does an object become eligible for garbage collection? What are GC roots?
Why doesn't Java have destructors, and how do you release resources like files?
List the operations that throw NullPointerException and three that are safe with null.
How can a garbage-collected Java program still leak memory? Give two examples and fixes.
Expected output
1: Cannot invoke "String.length()" because "Main.name" is null
2: Cannot invoke "String.trim()" because the return value of "Main.find(String)" is null
3: Cannot read field "name" because "Main.owner.pet" is null
4: name must not be null