Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Donna Thompson   on May 19 In Java Category.

  
Question Answered By: Oscar Evans   on May 19

The assert  keyword was new with 1.4 and allows you to add switches
that can be turned on and off to assist in debugging during and after
delpoyment. For example, say you need to test the value of an
integer "j", which must be greater than zero. In your code, simply
write:

assert j>0: "j is zero or less!";

then, when you run the program, provide a switch on the command line
like this:

java -ea (class file name)

which means "enable assertions"

...if the value of j is zero or less Java will throw an
AssertionError (provided in java.lang) to let you know. Assertions
are off by default, so when the application is deployed, if there are
errors, you can check them by turning them back on.

FYI, what is actually happening in the above "assert j>0" code the
long way round is:

if (j<0) throw new java.lang.AssertionError("j is zero or less");

...hope this helps, if any of this is wrong someone please let me
know. I am new to this group today and worked at Sun Microsystems for
4 years and am about to start for the Financial Times. Name's Dave G,
happy to know you all!

Share: