java null pointer exception

 

    We all know that java does not have pointers. The "java pointer" mentioned here refers to the reference of java. We will not discuss whether it is appropriate to call the pointer here, but only analyze the exception itself. A null pointer is a null reference, and the java null pointer exception is that the reference itself is null, but a method is called, and a null pointer exception occurs at this time. It can be understood that member variables and methods belong to the object (except static), and the corresponding member variables and methods exist in the object, and then these member variables and methods are called through the object. For a null pointer, it does not point to any object, so there are no so-called member variables and methods. At this time, if you use it to call some properties and methods, of course, a null pointer exception will occur.

copy code
1 public class Test {
 2     private int a=1;
 3     private int b=2;
 4     public static void main(String[] args) {
 5         // TODO Auto-generated method stub
 6         Test t1 = new Test();
 7         Test t2 = null;
 8         System.out.println(t1.a);
 9         System.out.println(t2.a);
10         System.out.println(t2.c());
11     }
12     public String c(){
13         return "123";
14     }
15 }
copy code

We analyze the above sample code. In the Test class, there are two member variables a and b, and a method c(). Then in the main() method, we create two objects t1 and t2, where t1 points to the Test object instantiated by the constructor, and t2 is just a declaration and points to the null, not to the actual object. When debugging, the first output statement can be compiled, and when the second output statement is executed, because the null pointer calls a that does not belong to it, the program terminates and a null pointer exception is reported. Similarly, comment the second output statement. When the program executes the third output statement, the same error will occur because the c() method that does not belong to it is called.

 

2. How to solve

    For every java programmer, it is almost inevitable to encounter a null pointer exception, especially for inexperienced beginners. And because its debugging and finding are more difficult than other exceptions, it often takes a lot of effort to solve it.

    First understand the null in java

    null is a very important concept in Java. null was originally designed to represent something missing, such as a missing user, resource, or something else. However, a year later, the troublesome null pointer exception brought a lot of harassment to Java programmers.

    null is a keyword in java, therefore, it cannot be written as NULL, Null, only null.

    null is the default value for all reference types, and if a reference is not made to point to an actual object, its default value is null. null is essentially a value, just like the default value of int is 0, and the default value of boolean is false. Now, we usually use an integrated development environment like eclipse for development. Generally, we will initialize variables when defining variables (this is also a good habit of writing code). If the initialization is not performed, the system will prompt.

Null pointer exceptions are reported for the following reasons: 

1. The string variable is not initialized; 
2. The object of the interface type is not initialized with a specific class, such as: 
List it; an error will be reported 
List it = new ArrayList() 
; There is no case where it is judged to be empty. You can try adding a line before the following code: 
if(rb!=null && rb!="") 
to: 
if(rb==null); 
if(rb!==null&&rb!="") or If("").equals(rb)) 
Null pointer solution: 
       focus on the line where the error occurs, and diagnose specific errors through the two main reasons for the null pointer exception. At the same time, in order to avoid the occurrence of null pointers, it is best to put "null" or null value before the set value when making judgment processing. 
A brief analysis of common null pointer exceptions: 
(1) Null pointer errors 
    There are 8 basic data types in Java. The value of the variable can have its default value. If it is added without a normal assignment to it, the java virtual machine cannot be compiled correctly. Therefore, Using basic Java data types generally does not cause null pointer exceptions. In actual development, most of the null pointer exceptions are mainly related to the operation of objects. 
    The following lists several situations in which a null pointer exception may occur and the corresponding solutions: 
    Code segment 1: 
  out.println(request.getParameter("username")); 
  Analysis: The function of code segment 1 is very simple, that is, to output user input" username" value. 
       Explanation: It appears that the above statement does not find any syntax errors, and in most cases no problems are encountered. However, if a user does not provide the value of the form field "username" when entering data, or bypasses the form for direct input in some way, the value of this request.getParameter("username") is empty (note that it is not empty). A string is an empty object null.), the println method of the out object cannot directly operate on the empty object, so the JSP page where the code segment 1 is located will throw a "Java.lang.NullPointerException" exception. And even when the object may be empty, some methods such as toString(), equal(Object obj), etc. of Java.lang.Object or the Object object itself are called. 
    Code snippet 2: 
  String userName = request.getParameter("username"); 
  If (userName.equals("root")) 
  {....} 
  Analysis: The function of code snippet 2 is to detect the username provided by the user, if it is When the user name is "root", some special operations are performed.                                                                        
      Explanation: In code snippet 2, if a user does not provide the form field "username" When the value of the string object userName is null, it is not possible to directly compare a null object with another object. Similarly, the JSP page where the code segment 2 is located will throw a null pointer error.
     A little trick: If you want to compare the return value of a method with a constant, put the constant first to avoid calling the equals method of the null object. for example:  
    If ("root".equals(userName)) 
  {....} 
    Even if the userName object returns a null object, there will be no null pointer exception here and it will work as usual. 
    Code segment 3: 
  String userName = session.getAttribute("session.username").toString(); 
        Analysis: The function of code segment 3 is to take out the value of session.username in the session and assign the value to the string object userName . 
       Note: Under normal circumstances, if the user is already in a session, there will be no problem; however, if the application server restarts at this time, and the user has not logged in again, (it may also be that the user closes the browser, but The original page is still opened.) Then, the value of the session will be invalid at this time, and the value of session.username in the session will be empty. Direct execution of the toString() operation on a null object will cause the system to throw a null pointer exception. 
    Code segment 4: 
public static void main(String args[]){ 
       Person p=null; 
       p.setName("Zhang San"); 
       System.out.println(p.getName()); 

Analysis: declare a Person object , and print out the Name name in the object. 
Note: At this time, your p will have a null pointer exception, because you only declared the object of type Person and did not create an object, so there is no address reference in its heap. Do not create it when you want to use the object use method. object.

 

 

    

 

 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325303886&siteId=291194637