Header Ads

  • Breaking Now

    What is an Assertion and why using assertion in your program is a good idea ?

    In a Java program,several times, one would like to make certain assumptions for executing a program.For example,while taking a square root of a numeric value it has to be assumed that this value should not be negative.An assertion is a statement in the Java programming language that enables to test assumptions about one's program.Assertions are supported from J2SE1.4 and later.A simple exmaple of assertion can be checking of an employee object from being null:

    Employee employee = null;

    //Get an Employee object

    //Ensure we have one
    assert emplyee!= null;

    This asserts that an employee is not null. If employee is null, an AssertionError is thrown. Any line of code executing after the assert statement can safely assume that employee is not null.

    Each assertion is a boolean statement when an assertion executes,it returns true and when it returns false then an error is thrown.So successful execution of an assumption will ensure an error free code.By including assertions in one's program,the following objectives can be achieved:

    -The quickest way of identifying and correcting bugs.
    -The code becomes less prone to errors hence better maintained against errors and more efficient.
    -Better readability of code.

    Post Top Ad

    Post Bottom Ad