Java NullPointerException
NullPointer Exception is an exception in java that is very frequent to arise with the programmers. It is a runtime exception that occurs when the object instantiation is not proper. The object is declared as having a null value in it. The null pointer exception simply signifies that it is trying to call an object with a reference that has a null value in it. The most important thing to keep in mind is that the null pointer exception is not related to pointers as the java language does not support the pointer concept; rather, it is associated with object references.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
There is no specific syntax for the Null pointer exception to specify as a run time error; it automatically arises and becomes visible for use.
A catch exception can be declared and then thrown to point and debug for the NullPointer Exception. It’s a very tedious thing to debug for the NullPointerException. It is needed to make sure that the object instantiation and reference declaration are proper at the execution time.
try { Object obj1 = new Object(); // Instantiate a new object for the class as reference Obj1=null; //Provide null value to the object created Logging.log(String.format(“get the object value”, obj1.object1for reference)); } catch(java.lang.NullPointerException exception) { Logging.log(exception); } catch(Throwable exception) { Logging.log(exception,false); }
How NullPointerException Work in Java?
NullPointerException in Java is an exception that is not at all a preferable error for a developer. It is very difficult to find the exception as it occurs every time at the runtime. Therefore, finding such an exception is a tedious task. It takes hours for the programmers to find out the NullPointerException.
It arises when an unusual attempt is made to assign the object defined with the null anywhere when an object is required for some other thing. All the java errors, including NullPointerException, occurs due to certain reasons such as:
- Whenever java.lang.the throwable interface is declared it will throw all the possible java errors and further gets extended by inherited class.
- lang.Exception then gets inherits from the java.lang.throwable.
- lang.throwable class extends the java.lang.exception.
- Even Java.lang.RuntimeException also occurs due to this inherited class.
- Eventually, java.lang.NullPointerException gets inherited from the java.lang.RuntimeException class.
As it is clearly mentioned and seen that the NullPointerException gets inherited from the java.lang.RuntimeException this issue will arise whenever there is an execution of the application at the time of compilation and execution of the application. Also, whenever it is tried to directly access a field, method, or the incorrect reference of the object at the time of instantiation, then it is very much needed to throw the java.lang.NullPointerException. Adding loggers and then creating a further dummy object and then calling the instance of the method of the null assigned object also helps in proper debugging of the code and finding the root cause of the NullPointerException and the lines pointed to the error and the exception. Thus, it is a very conventional method of troubleshooting and debugging for understanding the java error occurring on the specific line.
Constructors of Java NullPointerException
There are certain specific constructors defined and declared with the method of the NullPointerException, which are as follows:
1. NullPointerException()
This constructor is used to construct a NullPointerException with no detailed message or explanation. It can be considered an empty or null exception that is not as much recommended as per requirement.
2. NullPointerException(String s)
This constructor behaves contradictory to the NullPointerException() as it includes a bit of the detailed message causing at the specified location, and it will involve the argument which can be used at the time of constructing a null pointer exception. The argument String s is responsible for creating the null pointer exception with the detailed message.
Examples to Implement of Java NullPointerException
Below are the examples of Java NullPointerException:
Example #1
This program is used to demonstrate the invalid method’s invocation at the time of execution, which results in NullPointerException, which is not required.
Code:
public class Null_Pointer_Excptn { public static void main(String[] args) { String strng = null; try { if (strng.equals("monkey")) System.out.println("Let us take a value which needs to be similar"); else System.out.println("Otherwise it will not take a similar and equal value."); } catch(NullPointerException e) { System.out.println("It is a need to catch the null pointer exception."); } } }
Output:
Example #2
This program illustrates the java program, which avoids the creation of NullPointerException as it is not a conventional method.
Code:
public class Null_Pointer_Excptn_Avoid { public static void main(String[] args) { String strng2 = null; try { if ("avoid_null".equals(strng2)) System.out.println("Coming out to be equal"); else System.out.println("It is not at all coming out to be equal"); } catch(NullPointerException e) { System.out.println("Catch the null pointer Exception to get a clarification."); } } }
Output:
Example #3
This program illustrates that the NullPointerException can be avoided using the proper object verification before initialization.
Code:
public class Good_Null_Pntr_Excpn { public static void main(String[] args) { String store = "Learning"; try { System.out.println(getLength(store)); } catch(IllegalArgumentException e) { System.out.println("Need to catch the definition of illegalArgument."); } store = "Educba"; try { System.out.println(getLength(store)); } catch(IllegalArgumentException e) { System.out.println("Need to catch the definition of illegalArgument."); } store = null; try { System.out.println(getLength(store)); } catch(IllegalArgumentException e) { System.out.println("Need to catch the definition of illegalArgument."); } } public static int getLength(String store) { if (store == null) throw new IllegalArgumentException("Need to catch the definition of illegalArgument."); return store.length(); } }
Output:
How to Avoid NullPointerException?
As it is not a good practice to get NullPointerException as it makes the entire codebase cumbersome and consumes time for the programmers to figure out the root cause of the NullPointerException.
Therefore, it is very much needed to avoid these exceptions which can make sure using the following ways:
- By comparing a string with the literals.
- By keeping a check on the passed arguments or parameters being passed from the method.
- By making use of the ternary operator.
Conclusion
Java NullPointerException is an exception which is not a good option and is recommended not to occur as it consumes a lot of time. Debugging and troubleshooting become difficult; therefore, it must keep in mind that before the initialization of the object, the reference of the object must be proper. Therefore, the reference of the object’s null value should be proper, and then it can be avoided.
The above is the detailed content of Java NullPointerException. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
