«Back to Home

Core Java

Topics

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
  1. import java.util.Scanner;  
  2. public class AssertExample {  
  3.     public static void main(String args[]) {  
  4.         Scanner s = new Scanner(System.in);  
  5.         System.out.print("Enter Your age ");  
  6.         int value = s.nextInt();  
  7.         assert value >= 18"Sorry, not valid";  
  8.         System.out.println("Your age is " + value);  
  9.     }  
  10. }  
29
 
Output

30

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.