If you have the stacktrace, NullPointerExceptions are usually easy to spot with a bit of practice: It comes from calling a method or referencing an property on an object that is null. So look at the line that is reported and see what objects are being referenced. In your example:
thisHive.get("a").bees.set(thisHive.get("a").beeIndex, larvae);
Can thisHive
be null? what does get("a")
return? Can it be null? (yes it can because a map returns null if the key is not found). Can bees
be null? Etc. You can often spot it just looking at the code, but a debugger makes it even easier. Set a breakpoint on the line and see what is null. Then work backwards to understand why it is null.
One thing to be aware of is autoboxing: if you have a variable declared as a wrapper class (Long
,Integer
, Boolean
, etc.) and you reference it as a primitive, you will get a NPE:
private int getMyInt() {
Integer myInt = null;
return myInt;
}
private void doSomething() {
int i = getMyInt();
}