NullPointerException in Java

NullPointerException is a RuntimeException . Runtime exceptions are critical and cannot be caught at compile time. They crash the program at run time if they are not handled properly. When a class is instantiated, its object is stored in computer memory. The NullPointerExceptions occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. These include:
  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Throwing null as if it were a Throwable value.
Example:
String str; str = new String("Java");
The first line declares a variable named str, but, it does not contain a primitive value. Instead it contains a pointer (because the type is String which is a reference type). Since you did not say as yet what to point to Java sets it to null . That means its pointing at nothing.

In the second line, the new keyword is used to instantiate (or create) an object of type String and the pointer variable str is assigned this object. You can now reference the object using the dereferencing operator . (a dot).

String str; str = new String("Java"); System.out.println("Length :"+str.length());

The above code is to find the length of the string. When you run the code, it will output the result as 4.

The NullPointerException occurs when you declare a variable but did not create an object. If you attempt to dereference str before creating the object you get a NullPointerException. Check the following code:
String str=null; System.out.println("Length :"+str.length());
The first line declares a variable named str and set to null. In the second line, you try to find the length of the String without instantiate (or create) an object of type String using "new" keyword. When you compile the code, the compiler generate .class file without any errors. But, when you run the above code, you will get "Exception in thread "main" java.lang.NullPointerException" . Here this exception is raised because when you try to access members from a class using object reference that is initialized to null value.

How to fix Java NullPointerException?

You can avoid this NullPointerException by coding like this:

if(str != null){ //do something } else { //do something }
Note: In order to fix this NullPointerException you should always initialize your objects before you try to do anything with them.