Java from zero: null is not an object
A variable can hold null, which means no object. Calling a method on null fails. The program checks first and prints missing.
Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.
An object variable can hold an object, or it can hold null. null means there is no object. Calling label() on null throws NullPointerException and the program stops. The tip is to look before you call.
Null is a reference to no object#
A variable of class type holds a reference, not the object itself. Null is the reference that points nowhere. The bits of the variable exist. The fields do not. Calling label follows the reference, finds nothing, and throws NullPointerException. The program in this lesson asks the question before the call, so the throw never happens and the printed word is missing. The check is the lesson. A primitive such as int cannot be null, because it is not a reference.
- item.label()nullthrows
public class Main {
static class Item {
String name;
int cents;
Item(String name, int cents) {
this.name = name;
this.cents = cents;
}
String label() {
return String.format("%s $%d.%02d", name, cents / 100, cents % 100);
}
}
public static void main(String[] args) {
Item item = null;
String text = item == null ? "missing" : item.label();
System.out.println(text);
}
}
missing
The check is the whole tip#
Item item = null is a legal variable. The type is Item. The value is no item. item == null is true, so the ? : expression picks "missing" and never calls label. If you delete the check, item.label() throws, and the stack trace points at that line.
int cannot be null. Only object types can. String word = null is allowed, and word.length() throws the same way. A field you forgot to set in a constructor is also null when its type is a class. Set it in the constructor, or check it at the call.
missing is a choice you printed#
The program did not invent a price. It said the order is not there. That is easier to read than a stack trace, and it is what you want when a missing order is a normal case. When a missing order is a bug, let it throw, and fix the line that stored null. The next lesson is a different quiet bug: integer division.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.