In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.
Object obj = null;
But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.
Following are some scenarios where NullPointerException occurs.
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)
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)
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)
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)
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)
To avoid NullPointerException
Yes, you can handle NullPointerException in the main method and display your own message. And, if you haven’t handled it the program terminates abnormally throwing NPE at the run time.
public class Demo { public static void main(String args[]) { int myArray[] = null; try { System.out.println(myArray[5]); }catch(NullPointerException e){ System.out.println("NPE occurred"); } } }
NPE occurred
But, Since NullPointerException is a Runtime/unchecked exception there is no need to handle it at run time.
Moreover NPE occurs whenever there is a bug in the program which should be fixed, it is recommended to fix the bug or avoid it instead of trying to catch the exception.