Wednesday 6 February 2019


                                                 java.lang.NullPointerException


NullPointerException is a runtime exception, so we don’t need to catch it in program. NullPointerException is raised in an application when we are trying to do some operation on null where an object is required. Some of the common reasons for NullPointerException in java programs are;
  1. Invoking a method on an object instance but at runtime the object is null.
  2. Accessing variables of an object instance that is null at runtime.
  3. Throwing null in the program
  4. Accessing index or modifying value of an index of an array that is null
  5. Checking length of an array that is null at runtime.

case:-1 NullPointerException when calling instance method
public class TestNullPointer {

public static void main(String[] args) {

TestNullPointer t = marJava();

t.mitJava("nam tere kar java");

}

private static TestNullPointer marJava() {
return null;
}

public void mitJava(String s) {
System.out.println(s.toLowerCase());
}
}





===========================================================================================================================
case:-2 Java NullPointerException while accessing/modifying field of null object


public class TestNullPointer1 {

public int marjava = 10;

public static void main(String[] args) {

TestNullPointer1 t = mitJava();

int namterekarjava = t.marjava ;

}

private static TestNullPointer1 mitJava() {
return null;
}

}






===============================================================================================================================
case:-3 Java NullPointerException when null is passed in method argument



public class TestNullPointer2 {

public static void main(String[] args) {

marJava(null);

}

public static void marJava(String s) {
System.out.println(s.toLowerCase());
}
}


=================================================================================================================================
case:-4 java.lang.NullPointerException when null is thrown

public class TestNullPointer3{

public static void main(String[] args) {

throw null;
}

}




===============================================================================================================================
case:-5 java.lang.NullPointerException when getting length of null array

public class TestNullPointer4{

public static void main(String[] args) {

int[] marjava = null;

int len = marjava .length;
}

}


================================================================================================================================
case:6 NullPointerException when accessing index value of null array

public class TestNullPointer5 {

public static void main(String[] args) {

int[] marjava= null;

int len = marjava[2];
}

}

===============================================================================================================================

case:7 java.lang.NullPointerException when synchronized on null object

public class TestNullPointer6 {

public static String marjava = null;

public static void main(String[] args) {

synchronized(marjava) {
System.out.println("synchronized block");
}

}

}


================================================================================================================================



case:-8 HTTP Status 500 java.lang.NullPointerException

Sometimes we get an error page being sent as java web application response with error message as “HTTP Status 500 – Internal Server Error” and root cause as java.lang.NullPointerException.

For this I edited the Spring MVC Example project and changed the HomeController method as below.


@RequestMapping(value = "/user", method = RequestMethod.POST)
public String user(@Validated User user, Model model) {
System.out.println("User Page Requested");
System.out.println("User Name: "+user.getUserName().toLowerCase());
System.out.println("User ID: "+user.getUserId().toLowerCase());
model.addAttribute("userName", user.getUserName());
return "user";
}






o/p:-----------------------


HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is java.lang.NullPointerException

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


Note:----------------
Root cause is NullPointerException in statement user.getUserId().toLowerCase() because user.getUserId() is returning null.





                                            How to fix java.lang.NullPointerException



java.lang.NullPointerException is an unchecked exception, so we don’t have to catch it. Usually null pointer exceptions can be prevented using null checks and preventive coding techniques. Look at below code examples showing how to avoid java.lang.NullPointerException.
================================================================================================

if(mutex ==null) marjava =""; //preventive coding

synchronized(marjava ) {
System.out.println("synchronized block");
}


========================================================================================================


//using null checks
if(user!=null && user.getUserName() !=null) {
System.out.println("User Name: "+user.getUserName().toLowerCase());
}
if(user!=null && user.getUserName() !=null) {
System.out.println("User ID: "+user.getUserId().toLowerCase());
}

=================================================================================================================


public void mitJava(String s) {
if(s.equals("Test")) {
        System.out.println("test");
    }
}


=================================================================================================================


public void mitJava(String s) {
if ("Test".equals(s)) {
System.out.println("test");
}
}



=====================================================================================================================


public int getArrayLength(Object[] array) {

if(array == null) throw new IllegalArgumentException("array is null");

return array.length;
}



========================================================================================================================

String msg = (str == null) ? "" : str.substring(0, str.length()-1);


=========================================================================================================================

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

============================================================================================================================


Object mutex = null;

//prints null
System.out.println(String.valueOf(mutex));

//will throw java.lang.NullPointerException
System.out.println(mutex.toString());




There are some methods defined in collection classes to avoid NullPointerException, use them. For example contains(), containsKey() and containsValue().













No comments:

Post a Comment