top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is a Null Pointer Exception in Java and how can I fix it?

+2 votes
641 views
What is a Null Pointer Exception in Java and how can I fix it?
posted Oct 13, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

public class NullPointerException extends RuntimeException

Thrown when an application attempts to use null in a case where an object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

Since:
JDK1.0

answer Oct 13, 2014 by Pushkar K Mishra
0 votes

NullPointerException is an unchecked exception & extends RuntimeException.

1) Invoking methods on an object which is not initialized
2) Parameters passed in a method are null
3) Calling toString() method on object which is null
4) Comparing object properties in if block without checking null equality
5) Incorrect configuration for frameworks like spring which works on dependency injection
6) Using synchronized on an object which is null
7) Chained statements i.e. multiple method calls in a single statement

To avoid this exception by using following ways:
1) String comparison with literals

ex: String str=null;
if("test".equals(str)){   
}
//use this instead of
if(str.equals("Test")){
}

2) Check the argus of method

void method(String s){
if(s==null) throws exception

3) Prefer String.valueOf() method instead of toString()

4) Use Ternary operator

5) Create methods that return empty collections instead of null

6) If your application code makes use of collections then use Use the contains(), containsKey(), containsValue() methods

7) Use Assertions

public static int getLength(String s) {
     assert (s != null);
     return s.length();
}

8) Check the return value of external methods

And in the last don't forget to do the unit test.

(Not my creation found it on the net)

answer Oct 13, 2014 by Salil Agrawal
...