Thursday, February 5, 2015

Assertions in Java

When creating application programs, you assume many things. However, often it happens that the assumptions don’t hold, resulting in an erroneous condition. The assert statement is used to check or test your assumptions about the program. In this article, we try to understand how and when to use assert keyword in Java.

There are many reasons why you should add assertions to the program. One reason is that it helps find the problems early; when you check your assumptions in the program, and when any of them fail, you immediately know where to look out for the problem and what to fix. Also, when other programmers read your code with assertions, they will be in a better position to understand the code because you are making your assumptions explicit using assertions.


The keyword assert provides support for assertions in Java. Each assertion statement contains a Boolean expression

  • If the result of the Boolean expression is true, it means the assumption is true, nothing happens. 
  • However, if the Boolean result is false, then the assumption you had about the program holds no more, and an AssertionError is thrown. 

Remember that the Error class and its derived classes indicate serious runtime errors and are not meant to be handled. In the same way, if an AssertionError is thrown, the best course of action is not to catch the exception and to allow the program to terminate. After that, you need to examine why the assumption did not hold true and then fix the program.


A simple assertion is a statement of the form:

assert logical_expression;

Here, assert is a keyword, and logical_expression is any expression that results in a value of true or false . When this statement executes, if logical_expression evaluates to true , then the program continues normally. If logical_expression evaluates to false , the program is terminated with an error message starting with: java.lang.AssertionError. This is followed by more information about where the error occurred in the code. When this occurs, the program is said to assert.


Assert Statement
Assert statements in Java are of two forms:

  • assert booleanExpression;
  • assert booleanExpression : "Detailed error message string";

It is a compiler error if a non-Boolean expression is used within the assert statement.

Example
In this program, you are checking if the value of i is < 0; you are using the expression –i to convert it to a positive value. Once the condition check if (i < 0) is completed, the value of i cannot be negative, or that is your assumption. Such assumptions can be asserted with an assert statement.
The program will run fine if the Boolean expression (i >= 0) evaluates to true. However, if it evaluates to false, the program will crash by throwing an AssertionError.
Output:
Yes, this program executed successfully without throwing any exceptions.

Is there any value of i for which the condition will fail? Yes, there is! If the value of i is a minimum possible value of integer, then it cannot be converted into a positive value. Why? Remember that the range of integers is -2^31 to 2^31 – 1, so the integer values the value of i as –2147483648 to 2147483647. In other words, the positive value 2147483648 is not in the range of integers. So, if the value of i is –2147483648, then the expression -i will overflow and again result in the value –2147483648. Thus, your assumption is not true.

int i = Integer.MIN_VALUE;

Output

Enable/Disable Assertion
You saw that assertions are disabled at runtime; to enable assertions at runtime, use an -ea switch.To disable assertions at runtime, use a -da switch. If assertions are disabled by default at runtime, then what is the use of -da switch? There are many uses. For example, if you want to enable assertions for all classes within a given package and want to disable asserts in a specific class in that package, then a -da switch is useful.



How Not to Use Asserts
The key to understanding assertions is that they are useful for debugging and testing applications, and assertions are meant to be disabled when the application is deployed to end users.

  • Don’t use assertions for validating input values or for validating arguments to public methods. For signaling such runtime failures, use exceptions instead.
  • Don’t use assertions to check conditions that are required for the correct functioning of the application. Since assertions are disabled by default at runtime, the application will not function correctly when the asserted conditions are not present in the code.
  • The Boolean expressions given inside assert statements should not have side effects— modifying variable values, printing values to console, etc. In other words, the functioning of the application should remain the same no matter if assertions are enabled or disabled.


If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

4 comments:

  1. Thanks for sharing your knowledge!
    Kudos from KZ, Central Asia

    ReplyDelete
  2. Thank you for sharing this.
    Chanakya Defence Group Guaranteed Success offers coaching for CDS/OTA written exams.
    CDS Coaching in Jammu

    ReplyDelete
  3. I appreciate the excellent writing in your article. It is full of interesting details and informative details. I appreciate you giving this useful information; it was quite beneficial. Please read this article about Color Blindness to understand more about color vision deficiency. Details regarding it have been provided in this post. Please feel free to visit and share your thoughts.

    ReplyDelete