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:
If some variable can be null
then should be checked before usage by if
instruction.
xxxxxxxxxx
1
// some code...
2
3
if(myVariable != null) {
4
// do some operation with myVariable...
5
}
6
7
// some code...
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).
xxxxxxxxxx
1
// some code...
2
3
assert myVariable != null : "Variable can not be null";
4
5
// 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.
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
String a = "text"; // or = null by default
5
6
// some code...
7
8
a = null; // for example: some operation caused null value
9
10
// some code...
11
12
System.out.println(a.length());
13
}
14
}
Output:
xxxxxxxxxx
1
Exception in thread "main" java.lang.NullPointerException
2
at Program.main(Program.java:12)
3
4
Process finished with exit code 1
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
String a = "text"; // or = null by default
5
6
// some code...
7
8
a = null; // for example: some operation caused null value
9
10
// some code...
11
12
if(a != null) {
13
System.out.println(a.length());
14
} else {
15
// other scenario...
16
}
17
}
18
}
Output (empty because nothing happened):
xxxxxxxxxx
1
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
String a = "text"; // or = null by default
5
6
// some code...
7
8
a = null; // for example: some operation caused null value
9
10
// some code...
11
12
assert a != null : "Variable can not be null";
13
14
System.out.println(a.length());
15
}
16
}
Output:
xxxxxxxxxx
1
Exception in thread "main" java.lang.AssertionError: Variable can not be null
2
at Program.main(Program.java:12)
3
4
Process finished with exit code 1
Note:
AssertionError
occured becausea != null
condition retunredfalse
. Programmer who used source code knows he made mistake.