English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Java, each type has a default value, and when you do not initialize the instance variables of a class, the Java compiler will use these values to initialize them for you. Null is the default value for the object type, and you can also manually assign null to an object in a method.
Object obj = null;
However, you cannot use an object with a null value or (if you use a null value instead of an object) an object, which will causeNullPointerException.
Here are some situations where NullPointerException may occur.
Use a null object to call the a method (instance).
public class Demo { public void demoMethod() { System.out.println("Hello how are you"); } public static void main(String args[]) { Demo obj = null; obj.demoMethod(); } }
Exception in thread "main" java.lang.NullPointerException at july_set3.Demo.main(Demo.java:11)
Access, modify, and print the fields of a null value (object).
public class Demo { String name = "Krishna"; int age = 25; public static void main(String args[]) { Demo obj = null; System.out.println(obj.age); System.out.println(obj.name); } }
Exception in thread "main" java.lang.NullPointerException at july_set3.Demo.main(Demo.java:11)
Attempt to access (print/use in a statement) the length of a null value.
public class Demo { String name = null; public static void main(String args[]) { Demo obj = new Demo(); System.out.println(obj.name.length()); } }
Exception in thread "main" java.lang.NullPointerException at july_set3.Demo.main(Demo.java:7)
Throw a null value.
public class Demo { public static void main(String args[]) { throw null; } }
Exception in thread "main" java.lang.NullPointerException at july_set3.Demo.main(Demo.java:5)
Access or modify an element/slot with a null value.
public class Demo { public static void main(String args[]) { int myArray[] = null; catch(NullPointerException e){ } }
Exception in thread "main" java.lang.NullPointerException at july_set3.Demo.main(Demo.java:6)
Избегайте NullPointerException
Убедитесь, что все объекты инициализированы перед использованием.
Убедитесь, что каждая переменная-ссылка (объект, массив и т.д.) не null, перед тем как обращаться к полям и методам (если они есть).
Да, вы можете обработать NullPointerException в методе main и показать свои сообщения. И если его не обработали, программа завершится с выбросом исключения NPE в runtime.
public class Demo { public static void main(String args[]) { int myArray[] = null; try { catch(NullPointerException e){ } System.out.println("NPE occurred"); } } }
Результат вывода
NPE occurred
Однако, так как NullPointerException является runtime/unchecked exception, его не нужно обрабатывать в runtime.
Кроме того, если в программе есть ошибки, которые необходимо исправить, будет возникать NPE. Рекомендуется исправить или избежать этой ошибки, а не пытаться перехватить исключение.