Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

assert keyword

  Asked By: Donna    Date: May 19    Category: Java    Views: 984

what does "assert" keyword means?
please provide me with an example,
thank you so much



1 Answer Found

Answer #1    Answered By: Oscar Evans     Answered 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

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!

Didn't find what you were looking for? Find more on assert keyword Or get search suggestion and latest updates.