what is the difference between java assert and if () {} else exit;?
can i just use if () {} else exit instead of assert ?
A bit of google maybe ?
" The main thing you should keep in mind is that the if-else statement should be used for program flow control and the assert keyword should only be used for testing purposes. You should never use asserts to actually perform any operation required for your application to work properly. According to Sun's official Java documentation: "Each assertion contains a boolean expression that you believe will be true when the assertion executes." "
if else exit statement you will have to add a variable to disable it and it will be much more complicated. Though if it is a part of your programm and you intend to leave it here, use a if else exit statement. As I said, assertions are for testing only.you could, assert is specifically designed to assert some part of code,
assert will throw AssertionError if it fails to assert
Also See
can I just use
if () {} else exitinstead ofassert?
Yes you could, but ...
you wouldn't be able to turn of the test unless you made the condition depend on an extra flag (which makes it more complicated, etc),
you wouldn't get a chance to perform tidy-up in any enclosing finally block,
it would be more complicated to log the cause of the problem than if an AssertionError (or any other exception) was thrown, and
if your code needed to be reused (as-is) in another application, your calls to exit could be problematic.
if-else is for controlling the flow of your program. assert must not be used for this! Asserts are just for having "checkpoints" in your code to check conditions which "should always" match.
Asserts can be turned on or off when running a program so that you could enable the asserts on your development machine/integration environment and disable them in the released version.
The assert keyword will only trigger an exception when you enable the assertions with -ea on the command line. The if/else will always execute. On top of that the assert keyword allows to write less verbose code. Compare:
assert parameter != null;
to:
if( parameter != null )
{
}
else
{
}
if (prm == null) throw new Exception(...);. The assertions are just not made for that purpose, they are made so that when putting your program into production no useless tests are made (because your assertions are always supposed to be valid). Hence, they are removed from the production package.
assertand what it does?