Rework this sample. val should not be null with what you've done. You need to return NULL if count is 0 in finalize and change the null checks in the Avg* functions to asserts.