EN
Java - what is java.lang.NullPointerException and how to prevent it?
14
points
NullPoiterException
occurs when progremmer try to acces to object type variable that has been assigned with null
. It is caused because of programmer mistake. There are few solution how to prevent it:
1. Simple solution
1.1. If null
variable value can occur in logic scenario
If some variable can be null
then should be checked before usage by if
instruction.
// some code...
if(myVariable != null) {
// do some operation with myVariable...
}
// some code...
1.2. If null
variable value sould not occur in logic scenario
If programmer predicted null
value can happen but he wanted to tell others it is not his mistake but mistake of the person who used souce code (not read documentation where is information acout not null argument/variable).
// some code...
assert myVariable != null : "Variable can not be null";
// some code...
Notes:
assert
allows for code execution only ifa != null.
- assertions make source code more clear,
- read this article to enable assertions in your program.
2. NullPoiterException
variable example
2.1. Reproduced excetion example
public class Program {
public static void main(String[] args) {
String a = "text"; // or = null by default
// some code...
a = null; // for example: some operation caused null value
// some code...
System.out.println(a.length());
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at Program.main(Program.java:12)
Process finished with exit code 1
2.2. Solution 1 - with if
statement
public class Program {
public static void main(String[] args) {
String a = "text"; // or = null by default
// some code...
a = null; // for example: some operation caused null value
// some code...
if(a != null) {
System.out.println(a.length());
} else {
// other scenario...
}
}
}
Output (empty because nothing happened):
2.3. Solutuion 2 - with assert
keyword
public class Program {
public static void main(String[] args) {
String a = "text"; // or = null by default
// some code...
a = null; // for example: some operation caused null value
// some code...
assert a != null : "Variable can not be null";
System.out.println(a.length());
}
}
Output:
Exception in thread "main" java.lang.AssertionError: Variable can not be null
at Program.main(Program.java:12)
Process finished with exit code 1
Note:
AssertionError
occured becausea != null
condition retunredfalse
. Programmer who used source code knows he made mistake.