This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

The Debug notes < Java. Lang. NullPointerException problem >

In Java, null is referenced by an object as a special value to indicate that the object is currently pointing to an unknown chunk of memory data.

NullPointerException is thrown when the application uses or accesses a reference to an object that is equal to null.

Generate Java. Lang. NullPointerException of reasons for this problem basically has the following several aspects:

1. String variables are not initialized.

2. Objects of interface type are not initialized with a concrete class

Common mistakes include:

  • List stuList; In this case, a null pointer exception is reported;
  • List stuList = new ArrayList(); This way, no errors will be reported after initialization.

A null pointer exception is raised when the value of an object is null.

So in this case, to make the code work correctly, you can add a judgment before the code, such as: if(ObjId! = null);

A String can do the following:

If (objectStr! = = null &&! Equals (objectStr))

We can also check if the string is not empty:

If (objectStr! = = null &&! Equals (objectstr.trim ()))

4. Preferential useString. The valueOf ()Methods to replaceThe toString ()

You can avoid using the toString method of an object when your program code requires a string representation of that object. If the reference to the program code object is null, a NullPointerException error is thrown. Use the static string.valueof method, which does not throw any exceptions and prints NULL

5. Use ternary operators

We know this from the expression of the ternary operator

boolean expression ? value1 : value2;

Value1 is returned if expression is true, value2 is returned otherwise.

We can use the ternary operator to handle null Pointers, effectively avoid Java. Lang. NullPointerException.