2

How could this code throw a null pointer exception?

for (Foo f : Vector<Foo> v)
{
    f.doStuff(); // this line throws a NullPointerException
}

Even if the Vector is empty, shouldn't the inside block just never be executed?

1
  • 1
    Is the Vector empty? Did you run a debugger? What are the contents of v?
    – Atreys
    Aug 4, 2011 at 13:20

2 Answers 2

10

The Vector is not empty. As you say, if it was then the loop body would not be executed.

If you get an NPE on that line, it means that one (or more) of the elements of the Vector is null.


I should also point out that the example code is syntactically incorrect. It should probably read something like this:

Vector<Foo> v = ...    
for (Foo f : v)
{
    f.doStuff(); // this line throws a NullPointerException
}
3
  • 1
    +1, @wohanley, If your data structure allows null values, then simply perform a "check" before you proceed to "do stuff" - if(f != null){...}. But this may be a non-issue for you.
    – mre
    Aug 4, 2011 at 13:24
  • 1
    You also get NPE if the Vector itself is null.
    – user802421
    Aug 4, 2011 at 13:26
  • 2
    @user802421 Yes, but in a different line.
    – Marcelo
    Aug 4, 2011 at 13:37
0

The syntax that you show is incorrect, you can not declare both the step variable (Foo f) and the collection (Vector v) in the loop. You will get a NullPointerException if the collection (v in your example) is null. As noted above, you will also get a NullPointerException if the collection contains an element that is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.