Null pointer error java. lang. NullPointerException

Source: Internet
Author: User

 

 

 

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,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.