Thursday, April 25, 2024
HomeJavaTips on how to cope with NullPointerException in Java with Examples

Tips on how to cope with NullPointerException in Java with Examples


The java.lang.NullPointerException or NullPointerException in Java might be the primary error or exception you’ll face in Java. It is a real nightmare for freshmen in Java however fairly simple to resolve when you get acquainted with Exception dealing with in Java. What makes NullPointerException a little bit bit difficult to resolve is its identify which has a pointer in itself and Java doesn’t assist pointers like C++ or C, identical to you do not have a number of inheritances in Java. As a Java developer with 20 years of expertise, I’ve solved numerous quantity of NullPointerException and now I’ve developed a coding and debugging sense by which I can spot what inflicting a specific NullPointerException and how you can repair it. 

What’s NullPointerException in Java?

NullPointerException in Java is nothing however an error or exactly an exception that happens if we tried to carry out any operation on an object which is null. 

In Java reference variable factors to object created in heap however once you create a reference variable of sort object by default its factors to “null” and once you attempt to name any technique on null, attempt to entry any variable on null you’ll get this null pointer exception.

When does NullPointerException happens in Java?

Javadoc of java.lang.NullPointerException has outlined situation when it might happen:

1) Once you name the occasion technique on a null object. you will not get a null pointer exception for those who name a static technique or class technique on the null object as a result of the static technique would not require an occasion to name any technique.

2) Whereas accessing or altering any variable or discipline on a null object.

3) Throwing null when an Exception is anticipated to throw.

4) When getting the size of an array when the array is null.

5) Accessing or altering slots of null identical to an array.

6) Once you attempt to synchronize on a null object or utilizing null contained in the synchronized block in Java.

Now, we’ll see examples of NullPointerException for every of the above eventualities to get it proper and perceive it higher. You may as well see these free Java programming programs to be taught extra about NullPointerException in Java. 
java.lang.NullPointerException - Common Cause of NullPointerException in Java Example

Widespread Causes of NullPointerException in Java as Instance

Based mostly upon my expertise java.lang.NullPointerException repeats itself in numerous codecs, I’ve collected the most typical reason behind java.lang.NullPointerException in java code and defined them right here, we’ll use the next Commerce class for instance :

public class Commerce {
   
personal String image;
   
personal int worth;
   
public static String market;

   

public Commerce(String image, int worth) {
       
this.image = image;
       
this.worth = worth;
   
}

   

public int getPrice() {
       
return worth;
   
}

   

public void setPrice(int worth) {
       
this.worth = worth;
   
}

   

public String getSymbol() {
       
return image;
   
}

   

public void setSymbol(String image) {
       
this.image = image;
   
}}

1. Java  NullPointerException whereas calling occasion technique on null object

That is most likely the most typical reason behind this error, you name technique on some object and located that the reference is null, all the time carry out null examine for those who see chance of null earlier than calling any technique on object.

Commerce pennyStock = null;
pennyStock.getPrice(); //this may throw NullPointerException

Exception in thread “important” java.lang.NullPointerException
at check.NullPointerExceptionTest.important(NullPointerExceptionTest.java:23)




2. NullPointerException in Java whereas accessing discipline on a null reference.

Commerce fxtrade = null;
int worth = fxtrade.worth; //right here fxtrade is null, you possibly can’t entry discipline right here

Exception in thread “important” java.lang.NullPointerException
at check.NullPointerExceptionTest.important(NullPointerExceptionTest.java:64)

3. java.lang.NullPointerException when throwing null as an exception.

RuntimeException nullException = null;
throw nullException;

Exception in thread “important” java.lang.NullPointerException
at check.NullPointerExceptionTest.important(NullPointerExceptionTest.java:74)

4. instance of NullPointerException is when getting the size of an array that’s null.

Commerce[] bluechips = null;
int size = bluechips.size;  //array is null right here

Exception in thread “important” java.lang.NullPointerException
at check.NullPointerExceptionTest.important(NullPointerExceptionTest.java:85)

5. Instance of NPE when accessing a component of a null array.

Commerce[] bluechips = null;
Commerce motorola = bluechips[0]; //array is null right here

Exception in thread “important” java.lang.NullPointerException
at check.NullPointerExceptionTest.important(NullPointerExceptionTest.java:94)

6. Additionally, you will get NullPointerException in Java for those who attempt to synchronize on a null object or attempt to use the null object contained in the synchronized block in Java.

Commerce highbetaTrade = null;
synchronized(highbetaTrade){
System.out.print(“This assertion is synchronized on null”);
}


Exception in thread “important” java.lang.NullPointerException
at check.NullPointerExceptionTest.important(NullPointerExceptionTest.java:104)

Tips on how to resolve NullPointerException in Java

To resolve a NullPointerException in Java first we have to discover the foundation trigger, which may be very simple simply have a look at the stack-trace of NullPointerException and it’ll present the precise line quantity the place NPE has occurred. 


Now go to that line and search for potential object operations like accessing the sector, calling technique or throwing exception and so forth, that offers you an thought of which object is null. Now when you discovered that which object is null job is half carried out, now discover out why that object is null and resolve the java.lang.NullPointerException


This second half all the time very typically you get null object from the manufacturing facility or typically another thread might need set it null, although utilizing Assertion in early part of growth you possibly can reduce the probabilities of java.lang.NullPointerException however as I mentioned its little bit associated to the surroundings and might come on manufacturing even when examined nice in check surroundings.


It is greatest to keep away from NullPointerException by making use of cautious or defensive coding methods and null-safe API strategies.


When in Java Code NullPointerException would not come

1) Once you entry any static technique or static variable with null reference.

If you’re coping with static variables or static strategies you then will not get a null pointer exception even in case you have your reference variable pointing to null as a result of static variables and technique calls are bonded throughout compile time primarily based on the category identify and never related to an object. for instance beneath code will run nice and never throw NullPointerException as a result of “market” is an static variable inside Commerce Class.

Commerce lowBetaTrade = null;
String market = lowBetaTrade.market; //no NullPointerException market is static variable

Necessary factors on NullPointerException in Java

1) NullPointerException is an unchecked exception as a result of it extends RuntimeException and it doesn’t mandate try-catch block to deal with it.

2) Once you get NullPointerException to have a look at the road quantity to search out out which object is null, it might be an object which is asking any technique.

3) Trendy IDE like NetBeans and Eclipse offers you the hyperlink of the road the place NullPointerException happens

4) You may set an Exception break level in Eclipse to droop execution when NullPointerException happens learn 10 tips about java debugging in Eclipse for extra particulars.
5) Do not forget to see the identify of Thread on which NullPointerException happens. in multi-threading, NPE could be a little difficult if some random thread is setting a reference to null.

6) It is best to keep away from NullPointerException whereas coding by following some coding greatest practices or placing a null examine on the database as a constraint.

That’s all on What’s java.lang.NullPointerException, When it comes, and how you can resolve it. Within the subsequent a part of this tutorial, we’ll have a look at some greatest java coding practices to keep away from NullPointerException in Java.

Different Java debugging tutorial



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments