CKTIS / Java
The null literal
The null literal denotes a reference that does not point to any object. It has the special null type and can be assigned to variables of reference types, but not to variables of primitive types.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
nullnull is a literal denoting a reference that does not point to any object. It is neither a keyword nor the string "null". It has the special, unnamed null type, whose only value is the null reference. You cannot declare a variable of this type.
The value null can be assigned to a variable of any reference type, including a class, interface, or array type. It cannot be assigned directly to a primitive type: String text = null; is valid, whereas int count = null; causes a compile-time error. The empty string "" is a String object, not the value null.
The comparison text == null tests whether the reference is null; text != null tests the opposite. Calling an instance method through a null reference, such as text.length(), throws NullPointerException. In the example, assigning "" precedes that call, so the program prints true, false, and 0 in that order.
Examples
public class NullLiteralDemo {
public static void main(String[] args) {
String text = null;
System.out.println(text == null);
text = "";
System.out.println(text == null);
System.out.println(text.length());
}
}Result
true false 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.