Home > Java > javaTutorial > How to solve NullPointerException in Java?

How to solve NullPointerException in Java?

王林
Release: 2023-09-21 19:49:02
forward
1394 people have browsed it

How to solve NullPointerException in Java?

NullPointerException (null pointer exception) is a runtime exception thrown by the JVM when our application code, other referenced APIs or middleware encounter the following situations:

  • Try to call an instance method of an empty object.
  • Attempt to access or modify a specific field of an empty object.
  • Try to get the length of an empty object as an array.

Steps to resolve NullPointerException:

  • View the stack trace of java.lang.NullPointerException and determine where the exception is triggered (application code, third-party API, middleware software ), and extract the corresponding rows.
  • If the problem occurs in the application code, a code review is required. If the problem comes from a third-party API or middleware, you need to first look at the referenced code and determine whether it is indirectly the source of the problem, such as passing null values ​​to third-party API methods.
  • If a problem is found in the application code, try to determine which object instance is null and causing the problem. We need to modify the code to add proper null check validation and proper logging so that we can understand where the null values ​​are coming from.

Example

public class NPEDemo {
   private String field1 = null;
   private String field2 = null;
   public String getField1() {
      return field1;
   }
   private void setField1(String field1) {
      this.field1 = field1;
   }
   public String getField2() {
      return field2;
   }
   private void setField2(String field2) {
      this.field2 = field2;
   }
   public static void main(String[] args) {
      try {
         NPEDemo npe = new NPEDemo();
         npe.setField1("field1 value");
         npe = null;
         npe.setField2("field2 Value");
      } catch (Throwable e) {
         System.out.println("Java Error is: "+e );
         e.printStackTrace();
      }
   }
}
Copy after login

Output

Java Error is: java.lang.NullPointerException
java.lang.NullPointerException
at NPEDemo.main(NPEDemo.java:24)
Copy after login

The above is the detailed content of How to solve NullPointerException in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template