When the basic JAVA data type is used, the value of the variable is either the default value. If no value is assigned to the variable, the program cannot be compiled. Therefore, the basic JAVA data type (double, float, boolean, char, int, long) generally does not cause null pointer exceptions. It can be seen that null pointer exceptions are mainly related to object operations.
The following lists the possible situations and solutions for null pointer exceptions:
You can directly start using an object regardless of whether it is null.
(JSP) Code Segment 1:
Out. println (request. getParameter ("username "));
Description:
The function of section 1 is very simple, that is, to output the value of the user input form "username.
Note:
It seems that no syntax error is found in the preceding statement, and in most cases there are no problems. However, if a user does not provide the value of the form field "username" when entering data, or directly enters the form by bypassing the form in some way, request. the value of getParameter ("username") is null (not an empty string, it is a null object .), The println method of the out object cannot directly operate on the null object. Therefore, the JSP page where code segment 1 is located will throw a "java. lang. NullPointerException" exception.
Even if the Object may be empty, some methods of java. lang. Object or Object itself, such as toString () and equals (Object obj), are called.
(JSP) Code Segment 2:
String userName = request. getParameter ("username ");
If (userName. equals ("root "))
{....}
Description:
The function of section 2 is to check the user name provided by the user. If the user name is "root", special operations are performed.
Note:
In code snippet 2, if a user does not provide a value for the form field "username", The String object userName is null and cannot be directly compared with another object, similarly,