×

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are-

  1. Exception
  2. Error

Exception: If you are doing any wrong things in a program, then the exception occurs. If there are no wrong things, then there is no exception is appears. The exception can handle by exception handling tools.

Types of exception: The exception is mainly five types. These are –

  1. RuntimeException
  2. Input outputException
  3. SQLException
  4. InterruptedException
  5. ClassNotFoundException

RuntimeException: RuntimeException is also divided into many parts. These are:

  1. ArithmeticException
  2. NullPointerException
  3. NumberFormatException
  4. IndexOutOfBoundsException
    1. ArrayIndexOutOfBoundsException
    2. StringIndexOutOfBoundsException

NullPointerException: Here, we mainly discuss the NullPointerException and know how we can handle the NullPointerException in Java. The compiler prevents this exception in a few cases with the compile-time mistake "The variable won't be initialized". In contrast, a null reference variable is exceeded controversially:

String s;
foo(s);

NullPointerException is thrown whilst software tries to apply an item reference that has the null value. Those may be:

  1. Invoking a way from a null item.
  2. Getting access to or editing a null object’s discipline.
  3. Taking the length of null, as though it have been an array.
  4. Getting access to or modifying the slots of null object, as if it have been an array.
  5. Throwing null, as if it have been a Throwable fee.
  6. When you try to synchronize over a null item.

What is the need of null value?

The null value is a unique price used in java. It's explicitly used to signify that no fee is assigned to a reference variable. One utility of null is enforcing facts structures like related listing and tree. Different applications consist of a Null object sample (See this for details) and a Singleton sample. The Singleton sample guarantees that the best example of a category is created and pursued to supply a global factor of getting admission to the object. A sample manner to create at maximum one example of a class is to claim all its constructors as non-public and then create a public technique that returns the precise instance of the elegance.

Avoid the NullPointerException: Here, we discuss how the NullPointerException is avoided in java. To prevent the NullPointerException, we should ensure that every object is initialized nicely, earlier than you use them. When we claim a reference variable, we must verify that item isn't null before we request a technique or an area from the gadgets.

Example 1: Here we discuss the example of NullPointerException in Java.

class NullPointerException
{
public static void main (String[] args)
{
String str = null;
try
{
System.out.println (str.toUpperCase());
}
catch (NullPointerException n)
{
System.out.println (“null can not be printed”);
}
   }
}

Output: We compile the program and also run this program. After compilation the result is:

null can not be printed

Example 2: Here we discuss the example of NullPointerException in Java. The ternary operator can be used to keep away from NullPointerException. First, the Boolean expression is evaluated. If the expression is authentic then, the value1 is lower back, in any other case, the value2 is back. we will use the ternary operator for dealing with null suggestions:

import java.io.*;
class NullPointerException
{
public static void main (String[] args)
{
String str = null;
String message = (str == null)? “” ;
str.substring(0,8);
System.out.println (message);
str  = “NullPointerException”
message = (str == null) ? “” : str.substring(0,8);
System.out.println (message);
}
}

Output: We compile the program and also run this program. After compilation the result is:

Null

So, here we discuss how we can handle the NullPointerValue in java. We are talking about what exception is and how many types of exceptions exist. We write two programs in java on the topic NullPointerException and share the output of the given programs.


Related Topics

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.