English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Java, each type has a default value. When you do not initialize a class instance variable, 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.
The following are some situations where NullPointerException may occur.
Use a null object to call method a (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 (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 the length of a null value in a statement.
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 with a null value/slot.
public class Demo { public static void main(String args[]) { int myArray[] = null; System.out.println(myArray[5}); } }
Exception in thread "main" java.lang.NullPointerException at july_set3.Demo.main(Demo.java:6)
Avoid NullPointerException
Ensure that all objects have been initialized before using them.
Ensure that each reference variable (object, array, etc.) is not null before accessing its fields and methods (if any).
Yes, you can handle NullPointerException in the main method and display your own message. Moreover, if it has not been handled, the program will terminate with an exception at runtime.
public class Demo { public static void main(String args[]) { int myArray[] = null; try { System.out.println(myArray[5}); } System.out.println("NPE occurred"); } } }
Output Results
NPE occurred
However, since NullPointerException is a runtime/Unchecked exceptions, therefore, do not need to be handled at runtime.
Moreover, a NullPointerException (NPE) will occur if there are any errors that should be fixed in the program. It is recommended to fix or avoid the error instead of trying to catch exceptions.