GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||
GeezerVison is showing www.tutorialspoint.com — Java - NullPointerException
Selected Reading
Java - NullPointerExceptionA NullPointerException in Java occurs when an application tries to use an object reference that is null. This exception is a type of RuntimeException and does not need to be declared in a method's throws clause. This exception is a checked exception, meaning it must be either handled using a try-catch block or declared with the throws keyword. Reasons for NullPointerExceptionFollowing are the reasons when JVM throws a NullPointerException in Java:
Constructors of NullPointerExceptionThere are two constructors of NullPointerException class:
Methods of NullPointerExceptionThere are some methods of NullPointerException class:
Hierarchy of NullPointerExceptionGiven below is the class hierarchy of NullPointerException: java.lang.Object
└── java.lang.Throwable
└── java.lang.Exception
└── java.lang.ReflectiveOperationException
└── java.lang.NoSuchFieldException
Example of NullPointerExceptionIn this example, we are creating an object reference that is null, so JVM will throw a NullPointerException. public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length());
}
}
OutputFollowing is the output of the above code: Exception in thread "main" java.lang.NullPointerException at NullPointerExceptionExample.main(NullPointerExceptionExample.java:4) As you can see in the output, JVM throws a NullPointerException because we are trying to access the length of a null object. Handling NullPointerExceptionIn this example, we are creating an object reference that is null, so JVM will throw a NullPointerException. We are handling this exception using a try-catch block. public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Object reference is null");
}
}
}
OutputFollowing is the output of the above code: Object reference is null How to avoid NullPointerException?Following are the ways to avoid a NullPointerException:
SummaryNoSuchFieldException is a reflection-related error in Java that occurs when attempting to access non-existent fields. By following best practices and handling exceptions properly, developers can avoid runtime failures and build robust Java applications. java_lang_exceptions.htm Advertisements
| ||||||||
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |