Java throws the exception java.lang.NullPointerException, when you declare an object but do not instantiate it and yet use it for calling a class method or setting / getting variables.

Consider this code –

public class MyClass {
    public static void main(String args[]) {
      SuperHero superHero = null;

class SuperHero{
    private String name;
    private String weapon;
    public void SuperHero(String name, String weapon){ = name;
        this.weapon = weapon;
    public String get(){
        return name + ", " + weapon;

Here we are declaring SuperHero class object superHero and setting it to null. Now if we try to access the get() method of SuperHero class, we will get java.lang.NullPointerException.

Why nullPointerException happen?

For this, we need to understand all three terms – null, pointer and exception.

null is something which is isolated and do not have any property or value. It is used when we want to remove all links from some entity.

pointer is the memory address of the meaningful data. All the objects in java points towards the memory address using pointers.

exception is the way of saying that something is wrong with the code. It could be due to the bug in code or wrong data passed during runtime.

So, nullPointerException says that the object is null and it is not pointing to any meaningful data, hence you can not do the required operation over it.

But why will I do any operation over null object?

Yes, you won’t. But suppose you defined a method and you are accepting an object as argument for doing some operation over it then somebody else might call that method and pass null object in it. Look at this code –

public String getSuperHeroName(SuperHero supHero) {
   return supHero.get();

Now if somebody call this method with null as parameter, then exception will raise.


How to prevent nullPointerException?

You can take two paths – First, check for null and take action accordingly; Second, throw a custom message so that it could be more meaningful.

To check for null, use this code –

public String getSuperHeroName(SuperHero supHero) {
   if(supHero == null){
     return "This is not a Super Hero.";
   return supHero.get();

For sending custom message, use this code –

public String getSuperHeroName(SuperHero supHero) {
   Objects.requireNonNull(supHero, "SuperHero object is null");
   return supHero.get();

    Tweet this to help others