Cases where java.lang.nullpointerexception is thrown
We often have this error in our programs. java.lang.NullPointerException. This bug is started when you try to use a null object that has no value in the following cases:- Call a null method instance.
- Access or modify the instance of a null object.
- The exception is intended to throw.
- When calling the length of the null array. li>
- When accessing null locations such as an array.
- When synchronizing a null object or using it inside a synchronized block.
Objects are referenced by pointers in java
An object is a class instance or an array, references are pointers to these objects and a null reference is Refers to no object.When you declare a variable, Java sets the x variable to 0 and a pointer is created that references that object. For example, in the following code we will declare a variable x:
int x;In this example, the variable x is set to zero by default, and the second line, the value 5, is written to the memory location pointed to by x. Java forbids the programmer to manipulate memory boxes, it gives you access only to the object's methods and not the memory location.
x = 5;
Cases or NullPointerException is thrown
1) Call a method of a nullPoint dot = null;
dot.getX();
Exception in thread "main" java.lang.NullPointerException2) Access or modify the instance of a null object.
at Test.main(Test.java:27)
Point dot = null;
dot.getX();
Exception in thread "main" java.lang.NullPointerException3) When using throw null
at Test.main(Test.java:38)
throw verifies that the argument is non-null, and if it is zero, it rises NullPointerException.
IOException nullException = null;
try {
throw nullException;
} catch (IOException e) {
e.printStackTrace();
}
char[] ch = null;5) When accessing null locations such as an array
int length = ch.length;
An example is to access the boxes of a null.
char[] ch = null;
char c = ch[0];
6) When synchronizing a null
You get NullPointerException If you are trying to synchronize an object null or put it inside a synchronized block.
Thread th=null;
synchronized(th){
System.out.print("this thread is synchronized");
}
What are the preventions
- The best way to avoid this type of exception In case you didn't create the object yourself is to check if the object is zero. The code should be written like this:
void display(String phrase){This solution is not optimal in some cases because the object is null so nothing happens in the display() procedure.
//check if sentence is not null
if(phrase!=null)
System.out.print(phrase);
}
String string="";
//Declaration
Thread[] th=new Thread[3];
//Initialization
th[0]=new Thread();
th[1]=new Thread();
th[2]=new Thread();