Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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:
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:
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:
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:
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.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 21st December,2024 21st December SAT&SUN (Weekend Batch) | View Details |
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co