Avoiding NullPointerException in Java development

Source: Internet
Author: User

The exception of the null pointer is disgusting, I am afraid is the actual application of the most frequently occurring anomalies, the following is how to avoid nullpointerexception appearance of the technique

    1. Before using an object, it is best to know if they are possible null, and if not, use the IF statement to determine whether to use an object, or to traverse a collection, you need to make sure that they are non-empty. It's a rule that works in any situation.
      Object obj = service.getobj (); return obj.getsomefiled (); // null pointer exception appears
    2. The fields in the database are best set to be non-empty, that is, the default value is set, and objects accepted from the front end are also sentenced to null processing.
    3. It is a good idea to determine whether an object is empty until the underlying type is compared to the underlying type, unless you can fully guarantee that they are non-empty, that is, if the object is empty when unpacking automatically, for example:
      Integer count=obj.getcount (); if (0 < count) {  ... // null pointer exception appears }
    4. Use the Apache Lang Package tool class to convict empty and non-empty: StringUtils and Collectionutils

      if (Stringutils.isnotempty ()) {    ...}

Avoiding NullPointerException in Java development

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.