Java NullPointerException
Example
Call a method on a variable that is null, and catch the exception:
public class Main {
public static void main(String[] args) {
String text = null;
try {
System.out.println(text.length());
} catch (NullPointerException e) {
System.out.println("The text is null.");
}
}
}
Definition and Usage
A NullPointerException happens when you use a variable that does not point to an object (its value is null), for example to call a method on it.
Check that the variable is not null before you use it: if (text != null).
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions