How to Avoid Null Pointer Exception in Java

Null pointer exceptions are errors thrown by the Java compiler when the programmer attempts to use a variable that hasn't been defined. Other compilers, like Visual Basic, allow you to use variables that haven't been defined in the code, but languages like C, C++, C#, and Java do not allow use of a variable without defining it in the code. The following example shows why the error is displayed and how to avoid the error thrown when Java detects a null pointer.

Instructions

    • 1

      Define some variables. To simulate the error and to show why the exception happens, define some variables to use later in the code:
      int i = 2;
      int j = 2;

    • 2

      Attempt to add these two variables together and assign them to an undefined variable.
      x = j + i;
      This throws a null exception pointer because x is not defined in the code.

    • 3

      Avoid the null pointer exception by checking if the variable is null prior to using it. The code below avoids the null exception error.
      if (x != null) {
      x = j+i;
      }

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured