What is null pointer exception in java ? How to prevent?

Answer includes, null pointer exception in java with example when it can occur in programs and how we can prevent it.

Java interview Question: What is NullPointerException? Tell me some examples when this exception can occur in java programs. How would you prevent null pointer exceptions?

Answer:

null pointer exception is a run time exception and it is thrown when the program attempts to use an object reference that has null value. For example, calling a method or variable using an object which has null value or say object reference is null will cause run time exception.

In below sample code, String object is null and if we try to call any string method e.g. toLowerCase() then when we execute the program, then null pointer exception will be thrown.

public class Sample {

	public static void main(String[] args) {		
		
			String str=null;
			//Below will cause run time exception
			str.toLowerCase();		
	}
}

Here is the stack trace on running the above program

Exception in thread “main” java.lang.NullPointerException
at Sample.main(Sample.java:8)

Another example of null pointer exception , you can find with Object is null. example below.

public class Sample {

	public static void main(String[] args) {	
		
			Object obj=null;
			//Below will cause run time exception
			obj.hashCode();		
	}
}

Some more common situations when null pointer can occurs

  • When we invoke method on an object which is null or not initialized.
  • Pass an object which is null to a method as a parameter. foo(Object obj) //obj is null
  • Compare two strings e.g. String str=null; if(str.equal(“hi”))

How to prevent null pointer exception in java program?

To avoid or prevent null pointer exception we can put a null check on object then call methods. for example, in below program, first string str is checked if it is null then call the method that does not throw null pointer exception.

public class Sample {

	
	public static void main(String[] args) {		
		
			String str=null;
			//Check if String is not null then
			//call method
			if(str != null){
				System.out.println(str.toString());
			}
				
	}
}


As a conclusion,

If any class, whatever it is predefined or user defined object reference is null then calling class method will cause null pointer exception in java program.

To avoid it, always try to check the object with null in the code and then call operations or methods.

Related Posts