A literal (textual) expression of the null
value in source
code.
The null
literal is used to denote the special null value,
which cast to any reference type. There is only one null value whose
type is the null type. The null type cannot be expressed in Java code.
The Null Literal has one form:
1 | null |
1 The null
literal.
Parsed as a single token.
The null value is a special type of value that's used to represent the
lack of information. The null
literal is used to
explicitly write the null value in source code:
String x = null;
The null
value is assignable to any reference type,
including variables of any type parameter, even if the type is not
visible (see note 1).
Invoking a method on the null value results in a java.lang.NullPointerException
.
Doing so requires that the null
value be cast to some
reference type, such as String
:
int x = ((String) null).length(); // throws a NullPointerException
or more simply:
((String) null).length(); // throws a NullPointerException
null
The null
literal can be the operand of the throw
operator in a throw statement:
throw null;
This creates and throws a java.lang.NullPointerException
.
The null
literal can be used to call a function that has
parameters of inaccessible type. For example:
class A {
private static class Hidden {
}
public static void secureMethod(Hidden hidden) {
}
}
class B {
public static void test() {
// Call A.secureMethod(A.Hidden) without having an instance of the class, A.Hidden
A.secureMethod(null); // null is assignable to A.Hidden, so no instance of A.Hidden needed
// A.secureMethod(new A.Hidden()); // Not allowed; A.Hidden is private
}
}