In this blog I am sharing about what is Null Pointer Exception and how to fix it.
What Is NULL POINTER
In Java, when we are creating an object ie, Reference Variable, we create a pointer to that Object. Let us Consider the following case :
int x;
x=50;
In the above code, x is interger variable and compiler will assign 0 to it. But in the second line when x=50, in that case 50 will be stored in memory and x will point to it. But when we declare a reference type something different happens. Take the following code:
Interger x;
x=new Integer(50);
In this code, x will not contain any primitive data type like in previous 0 is stored, instead it holds the pointer and compiler will set to "null".and new keyword is used to create an object of type Integer.The pointer variable num is assigned to this object which can be used by .(dot) Operator. The NULLPOINTEREXCEPTION takes place when we declare a variable but do not create an object and we try to dereference num before creating object we get NULLPOINTEREXCEPTION.
How To Avoid NULLPOINTEREXCEPTION.
In order to fix the such Exception, we can perform following task.
- identifying exactly which values are causing Exception problem .
- we can either use debugger or logging statements.
- try to compare or identifiy the source and remove it.
Let us consider the following program
public class Demo {
private String name;
public void setName(String name) {
this.name = name;
}
public void demo() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Demo ob= new Demo();
ob.printString();
}
}
If we look above code we get some Exception Like this...
Exception in thread "main" java.lang.NullPointerException
at Demo.printString(Printer.java:13)
at Demo.print(Printer.java:9)
at Demo.main(Printer.java:19)
So we find that NULLPOINTEREXCEPTION is because of s.length() becuse it is null. so we can solve this by setting the Name before calling length() like below:
public class Demo {
private final String name;
public Demo(String name) {
this.name = Objects.requireNonNull(name);
}
public void print() {
printString(name);
}
private void printString(String s) {
System.out.println(s + " (" + s.length() + ")");
}
public static void main(String[] args) {
Demo ob = new Demo("50");
ob.print();
}
}
0 Comment(s)