Wednesday, April 24, 2019

Common Cause Of NullPointerException In Java

Q- How to preventing Null Pointer Exception (NullPointerException) in java? How to avoid NullPointerException In Java?

NullPointerException is a RuntimeException in java.
In Java, we can assign null value to an object reference and after that we assign some object reference to that reference. But while object also return null.
When program attempts to use an object reference that has the null value and try to get any method or propery on that reference than its thrown NullPointerException.

That means NullPointerException is thrown when program attempts to use an object reference that has the null value.

package com.shubh.example;

public class NullPointerException {

 public static void main(String[] args) {

  String str = null;
  int nullCheck = 0;
  int len = 0;
  if (nullCheck == 1) {
   str = new String("Hello Java");
   System.out.println("Print Length of string :" + len);
  }
  len = str.length();
  System.out.println("Print Length of string :" + len);
 }
}
 
Output:

Exception in thread "main" java.lang.NullPointerException
 at com.shubh.example.NullPointerException.main(NullPointerException.java:14)
 
As you see in this example we are not able to create instance of String class hence its throw NullPointerException

How to resolve this issue. : 
Before to call any method of that object first we need to chech if refference does not equals to null. as i do in my solution.

package com.shubh.example;

public class NullPointerException {

 public static void main(String[] args) {

  String str = null;
  int nullCheck = 0;
  int len = 0;
  if (nullCheck == 1) {
   str = new String("Hello Java");
   System.out.println("Print Length of string :" + len);
  }
  if (str != null) {
   len = str.length();
  }
  System.out.println("Print Length of string :" + len);
 }
}

Output:
Print Length of string :0

No comments:

Post a Comment