0

So I came across a bug caused by following example: I have static method

private static Foo findFoo(int id) {
  //we use id here not important
}

Then I used it inside another method like

private static updateFoo(final Integer id, final String newData) {
  final Foo existingData = findFoo(id);
  // use existing data and update or make new
}

The problem is when updateFoo is called with null in id argument, the intValue() is implicitly called (I think) when calling findFoo(id) and causes NPE.

I thought Java enforces strong typing that prevents cases where Objects are passed to arguments when primitives are expected. Is there a general rule here when implitic calls are made? And could this be picked up by compiler/IDE and possibly enforce or warn?

1 Answers1

1

This always happens if you use a wrapper class as its primitive counter-part. int cannot be null, so you must call intValue() onto the wrapper class.

You can either do a null check before calling findFoo() or just use the primitive int for updateFoo() or the wrapper class in findFoo().

I thought Java enforces strong typing that prevents cases where Objects are passed to arguments when primitives are expected.

The type of Integer fits, so its type is covered. It is just an implicite casting (unboxing) in this case which is totally fine.

Milgo
  • 2,617
  • 4
  • 22
  • 37