Languages
[Edit]
EN

Java - what is java.lang.NullPointerException and how to prevent it?

14 points
Created by:
Root-ssh
178170

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

Edit

1.1. If null variable value can occur in logic scenario

Edit

If some variable can be null then should be checked before usage by if instruction.

1.2. If null variable value sould not occur in logic scenario

Edit

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).

Notes:

  • assert allows for code execution only if a != null.
  • assertions make source code more clear,
  • read this article to enable assertions in your program.

2. NullPoiterException variable example

Edit

2.1. Reproduced excetion example

Edit

Output:

2.2. Solution 1 - with if statement

Edit

Output (empty because nothing happened):

2.3. Solutuion 2 - with assert keyword

Edit

Output:

Note: AssertionError occured because a != null condition retunred false. Programmer who used source code knows he made mistake.

See also

Edit
  1. Java - how to enable assertions? 
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join