I'm using the numberString = JOptionPane.showInputDialog(stuff) command. When Clicking on the Cancel button, I'm getting differing responses in two programs. On one program (which works), I'm checking for a null response by:
will run just fine, so long as the reference numberString is not a null reference. The boolean test of the if-statement will evaluate to false and skip the body - System.exit(0);.
If numberString were a null reference, then the boolean test of the if-statement would through an exception because you can't ask a null reference to do anything, like invoke a method of an object that isn't there.
I'll try to illustrate this point with another example.
Consider that I have a class Dog, which defines that Dog-type objects have a behavior called eat.
I could possibly have code such as the following:
Dog spot = new Dog("Spot"); spot.eat();
and everybody would be happy (and well-fed). This code creates a dog object, gives it the name Spot, points the reference spot to this dog object, and then invokes the method eat of this dog object.
What would the following code mean?
Dog lost = null; lost.eat();
What does this code do? It doesn't create a dog object. It initializes a Dog-type reference to null. It then tries to invoke the method eat on the dog object referenced by lost, but no dog object exists and lost doesn't refer to an object. That's a problem. In fact, that's a NullPointerException.
The lesson is: You can't invoke an instance method with a null reference.
if ( numberString == null )
This line of code is the proper way to test for a null reference. Note that no method is invoked with the reference.
Making sense? [ September 17, 2004: Message edited by: Dirk Schreckmann ]