Home  >  Article  >  Java  >  Java NullPointerException

Java NullPointerException

王林
王林Original
2024-08-30 16:13:03838browse

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:

Java NullPointerException

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:

Java NullPointerException

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:

Java NullPointerException

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:BinarySearch() in JavaNext article:BinarySearch() in Java