• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Testing for 'null', without producing a NullPointerException error message

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have written a method, that is occasionally passed a null object that I want to test for, and so 'filter out'. However, despite the "if Object == null" style of code, I get a NullPointerException error message at that same line, that I don't want, everytime I run the code.

My actual code is :-

if (parent.getChildren() != null)
{
do something
}

Here, 'parent' is an object of class 'TreeNode' (a class I have written), and 'parent.getChildren()' returns an object of type ArrayList<TreeNode>, which is just a list of TreeNode's. As, you may have guessed, I'm modelling a 'tree' data structure, which is a network of 'nodes', with connecting 'links', where each node has a parent node, as well as 'children' nodes too'.

When a node is instantiated, then initially it's parent node is set to null, and its list of child nodes is created as :- ArrayList<TreeNode> children = new ArrayList<TreeNode>(); , but then within the
constructor itself, I have set 'this.children = null'

Now, back to my point. How do I test for 'nullness' here, be able to handle it, without producing a NullReferenceException error?

Thanks
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
are you sure parent is not null? or rather...what exactly do you think you are testing for 'null-ness' here?

says "call the getChildren method on the object parent points to. However, if parent itself is null, you'll get the NPE. You may need to just do this:

or possibly even this:
 
Jeremy Watts
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
yeah, of course that is it... how dull of me :S thanks
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic