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:
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Throwing null as if it were a Throwable value.
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).
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:
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:
Note: In order to fix this NullPointerException you should always initialize your objects before you try to do anything with them.
- Java Interview Questions-Core Faq
- Important features of Java
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- Why do we need Generic Types in Java?
- What does it mean to be static in Java?
- What are final variables in Java?