Here's the context:
* Tom is being interrogated by the judge about the murder of Injun Joe.
* The judge, trying to throw Tom off, asks him if he can remember the details of a specific Sunday in June.
* Tom, trying to play dumb and avoid suspicion, answers "David and Goliath."
The humor lies in the unexpectedness of the answer. It's a nonsensical response to a serious question, and the absurdity of it makes it comical.
Mark Twain uses this scene to highlight Tom's resourcefulness and ability to think on his feet, even in a stressful situation. It also serves as a moment of comic relief in an otherwise tense scene.