If
x.doSomething();and x is null, you will raise an NPE (Null Pointer Exception). Note NullPointerException, not NullReferenceException.
The difference between a null reference and a reference to an empty object, (e.g. a freshly minted default object, empty collection or empty Iterator) is a major headache in Java. When dealing with other people’s code I want to strangle them. Why won’t they tell me when a method might return null or empty? Why won’t they tell me if a method can’t accept
if ( x != null ) { x.doSomething(); }must be the most common Java code fragment. I wish there were some more elegant way to handle this, that gives you the speed and space conservation of null, without the coding overhead bubblgum of checking for it at every turn. I have five solutions:
Obviously, if you null a reference it becomes a candidate for GC (Garbage Collection) sooner. In ordinary Java code, it is most common that you would exit the method almost immediately after such a nulling, so it buys you nothing for local variables allocated during the method invocation.
However, if you had some very complicated method, it could pay to null half-way through execution. But that being true is a symptom that you probably would want to refactor the routine in two, which would then most likely obviate the nulling.
|
|
available on the web at: |
http://mindprod.com/jgloss/null.html |
optional Replicator mirror
|
J:\mindprod\jgloss\null.html | |
![]() |
Please email your
feedback for publication,
letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear
wording, broken/redirected link reports, suggestions to improve this page or comments to
Roedy Green :
| |
| Blog | Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[23.22.252.150] |
|
| Feedback | You are visitor number 149,270. | |