Home >Java >javaTutorial >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:
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(); } } }
Java Error is: java.lang.NullPointerException java.lang.NullPointerException at NPEDemo.main(NPEDemo.java:24)
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!