Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Testing for Cancel Btn

 
Steve Booth
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

if ( numberString.equals( null ) ) {
System.exit( 0 );
}

On another program, this generates the NULLEXCEPTION error.

The instructor suggested:

if ( numberString == null ) {
System.exit( 0 );
}


but couldn't explain why.

Help?

TIA
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surely a difference in the programs.
Can you show us more code from the 'another' program?
From the declaration of numberString at least.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch, Steve!

I suspect that your different experiences could have been with different uses of a single program.

Note that the code

if ( numberString.equals( null ) ) {
System.exit( 0 );
}

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 ]
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic