Assertion In Java
Assertion
In Java, assertion is a statement and it can be used to test our assumptions about the program.
As executing assertion, it is supposed to be true. If it fails, JVM will throw an error named AssertionError. It is mostly used for the testing purpose. Assertion provides an effective way to detect and correct the programming errors in Java.
Syntax
There are two ways to use assertion, which are,
assert expression;
assert expression1 : expression2;
Let’s see an example, given below.
Code
- import java.util.Scanner;
- public class AssertExample {
- public static void main(String args[]) {
- Scanner s = new Scanner(System.in);
- System.out.print("Enter Your age ");
- int value = s.nextInt();
- assert value >= 18: "Sorry, not valid";
- System.out.println("Your age is " + value);
- }
- }
Output
In the example, mentioned above, we use assertion. It will not run simply because by default, assertion is disabled. To enable the assertion, -ea or -enableassertions switch of Java should be used.
Compile it by: javac AssertExample.java
Run it by: java -ea AssertExample
There are some situations, where an assertion should be avoided to use.
According to Sun, assertion should not be used to check the arguments in the public methods because it should result in proper runtime exception example IllegalArgumentException, NullPointerException etc. and do not use assertion, if we don't want any error in any situation.
Summary
Thus, we learnt that Java assertion is a statement, it can be used to test your assumptions about the program and also learnt how we can create it in Java.