Introduction
Assertions were added in Java 1.4 to create reliable programs that are correct and robust. Assertions are Boolean expressions that are used to test/validate the code. They are basically used during the testing and development phases. Assertions are used by programmers to be doubly sure about a particular condition, which they feel to be true.
Declaration of Assertions (syntax)
assert Expression1
In Java we declare Assertions with the help of the assert keyword. In this syntax, Expression1 is a Boolean expression; when the program is executed, the Expression1 in the assert is checked. If Expression1 returns true then the assertion set is true and the program runs without interruption. In the case when Expression1 returns false then an AssertionError is thrown and the Assertion makes the program fail.
assert Expression1:Expression2
In this syntax Expression1 has the same meaning as we explained above and the second Expression2 defines a string type statement that you want to show as an error message. This string type message is passed to the constructor of the AssertionError Object. If the Expression1 one returns false then the Expression2 value returns an error message.
public AssertionError()
This is the hierarchy of the AssertionError class in Java:
java.lang.Object
java.lang.Throwable
java.lang.Errorjava.lang.AssertionError
NOTE: Assertions must to be enabled explicitly; they are disabled by default. Using the -ea and -da option of Java, we can enable or disable assertions.
Example
class MyAssertion
{
static void ErrorCheck(int i)
{
assert i>0:"value must be Enter a possitive nuber";
System.out.println("you Enter a valid number ="+i);
}
public static void main(String arg[])
{
ErrorCheck(Integer.parseInt(arg[0]));
}
}
OUTPUT
Step 1 : When -ea is used and enter the value throw command line is -1.
Step 2 : When -ea is used and enter the value throw command line is 5 the output will be:
Step 3 : With out using -ea the output will be the same for both number -1 and 5.
Example
This example is made by using the assert keyword but using a single argument form like assert Expression1:
public class MyAssertion1
{
static int maxmarks=100;
static int changes(int mark)
{
maxmarks=maxmarks-mark;
System.out.println("maxmark:= " + maxmarks);
return maxmarks;
}
public static void main(String args[])
{
int g;
for(int i=0;i<5;i++)
{
g=changes(15);
assert maxmarks>=70.00;
}
}
}
OUTPUT
Without using -ea the output will be the same for both number -1 and 5.
Resources