How to avoid NULL pointer exceptions in Java

Source: Internet
Author: User
Tags assert empty exception handling

Null-pointer exceptions (null pointer Exception) are the most commonly encountered and most annoying exceptions. This article describes how to avoid null pointer exceptions.

First we look at the following example

Private Boolean isfinished (String status) {  
     if (status.equalsignorecase ("Finish")) {return  
       boolean.true;  
     } else {return  
       boolean.false;  
     }  
   }

If the value of status is empty, a null pointer exception appears (line 2nd of this example). So we should use the following methods

Private Boolean isfinished (String status) {
        if ("Finish". Equalsignorecase (status)) {return
            boolean.true;
        } else {return
            boolean.false;
        }
    }

In this case, the null pointer exception will not appear if the status is empty. I believe most of our friends already know this method, and if an object may be null, then you do not need to call its method directly.

Next I will provide several suggestions to avoid null pointers.

1. Judge whether the collection is empty.

2. Use some methods of judgment.

3.assert keywords.

4.Assert class.

5. Exception handling.

6. Too many points. Operation syntax.

7. Using the StringUtils class

1. Judge whether the collection is empty

Collection is null to mean that there are no elements in the Collection. Some developers often return NULL if they run into collection without elements, and better yet, you should return collections.empty_list,collections.empty_ Set or Collections.empty_map.

The wrong code

public static List GetEmployees () {  
   list list = null;  
   return list;  
 }

The right Code

public static List GetEmployees () {  
  list list = Collections.empty_list;  
  return list;  
}

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.