Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

Null Pointer Exception in Java: Implementation and Examples

Last updated on Jun 17,2021 9.1K Views


Exceptions are needed for the Smooth running of code and let programmers know the error to be solved. In this article, we will focus on Null Pointer Exception in Java in the following order:

 

What is Null Pointer Exception in Java?

The null pointer exception in Java is a runtime exception. In the world of Java, a special null value is assigned to an object reference. The Null Pointer Exception is introduced when a program attempts to use an object reference, which has the null value. Which can be:

  • To invoking a certain method from a null object.
  • To access or modify a null object’s field.
  • By considering the length of null, as if it were an array.
  • While accessing or modifying the slots of a null object.
  • Throwing null like a throwable value.
  • Trying to synchronize over a null object.

 

Why do we need the null value?

Null is a unique value used in Java. Null is used to show that no value is assigned to a reference variable. The primary application of null lies in implementing data structures like linked lists and trees. Some other applications include null object patterns and singleton patterns. A singleton pattern specifies that only one instance of a class can be initiated and aims for providing a global point of access to the object.

The best and simple way to create at least one instance of a class is to declare all the constructors as private. Then they create a public method that returns the unique instance of the class.

// To use randomUUID function. 
import java.util.UUID; 
import java.io.*; 
class Singleton 
{ 
	// Here we Initialize the values of single and ID to null. 
	private static Singleton single = null; 
	private String ID = null; 
	private Singleton() 
	{ 
		/* Make it private, in order to prevent the 
		creation of new instances of the Singleton 
		class. */
		// Create a random ID 
		ID = UUID.randomUUID().toString(); 
	} 
	public static Singleton getInstance() 
	{ 
		if (single == null) 
			single = new Singleton(); 
		return single; 
	} 
	public String getID() 
	{ 
		return this.ID; 
	} 
} 



// Driver Code 
public class TestSingleton 
{ 
	public static void main(String[] args) 
	{ 
		Singleton s = Singleton.getInstance(); 
		System.out.println(s.getID()); 
	} 
}
//

Output:

null-pointer

The above example is a static instance of the singleton class. The instance is initialized at most once inside the Singleton get Instance method.

 

How to avoid the Null Pointer Exception in Java?

In order to avoid the Null Pointer Exception in Java, we must make sure that all the objects are initialized properly before you use them. When a reference variable is declared, we must verify that an object is not null and also Before we request methods or fields from objects. The following are some problems with its corresponding solutions to overcome that problem.

//  program to demonstrate the invoking of a method 
// on null causes NullPointerException 
import java.io.*; 

class GFG 
{ 
	public static void main (String[] args) 
	{ 
		// Initializing String variable with null value 
		String ptr = null; 

		// Checking if ptr.equals null or works fine. 
		try
		{ 
			// This line of code throws NullPointerException 
			// because ptr is null 
			if (ptr.equals("gfg")) 
				System.out.print("Same"); 
			else
				System.out.print("Not Same"); 
		} 
		catch(NullPointerException e) 
		{ 
			System.out.print("NullPointerException Caught"); 
		} 
	} 
}

Output:

null-pointer-exception

 

 

Keeping a Check of the Arguments of a Method

Always remember that before executing the body of a new method, we should ensure its arguments for null values and continue with the execution of the method. If and only when the arguments are properly checked. Else, it will throw an “IllegalArgumentException” and call out the calling method that something is wrong with the passed arguments.

// program to check if parameters are null or not before 
// using them. 
import java.io.*; 
class GFG 
{ 
	public static void main (String[] args) 
	{ 
		// String s set an empty string and calling getLength() 
		String s = ""; 
		try
		{ 
			System.out.println(getLength(s)); 
		} 
		catch(IllegalArgumentException e) 
		{ 
			System.out.println("IllegalArgumentException caught"); 
		} 

		// String s set to a value and calling getLength() 
		s = "GeeksforGeeks"; 
		try
		{ 
			System.out.println(getLength(s)); 
		} 
		catch(IllegalArgumentException e) 
		{ 
			System.out.println("IllegalArgumentException caught"); 
		} 

		// Setting s as null and calling getLength() 
		s = null; 
		try
		{ 
			System.out.println(getLength(s)); 
		} 
		catch(IllegalArgumentException e) 
		{ 
			System.out.println("IllegalArgumentException caught"); 
		} 
	} 

	// Function to return length of string s. It throws 
	// IllegalArgumentException if s is null. 
	public static int getLength(String s) 
	{ 
		if (s == null) 
			throw new IllegalArgumentException("The argument cannot be null"); 
		return s.length(); 
	} 
}

Output:

Null Pointer Exception in Java

 

Use of Ternary Operator

A ternary operator is used to avoid NullPointerException. The Boolean expression is checked and if the expression is true then, the value1 is returned, otherwise, the value2 is returned. The ternary operator for handling null pointers can be used: The right image is the corresponding output.

// A Java program to demonstrate that we can use 
// ternary operator to avoid NullPointerException. 
import java.io.*; 
class GFG { 
	public static void main (String[] args) 
	{ 
		// Initializing String variable with null value 
		String str = null; 
		String message = (str == null) ? "" : 
						str.substring(0,5); 
		System.out.println(message);  
		str = "Edureka_Java_Blog"; 
		message = (str == null) ? "" : str.substring(0,5); 
		System.out.println(message); 
	} 
}

Output:

Edurek

 

With this, we come to the end of Null Pointer Exception in Java. I hope you got an idea of Null Pointer Exception.

Check out the Java Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Null Pointer Exception in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Null Pointer Exception in Java: Implementation and Examples

edureka.co