×

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

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.