Sunday 17 August 2014

Assert keyword in Java

An assertion is a statement, enables you test your assumptions in the program.

Assertion statement has two forms.
Syntax
1. assert Expression1 ;
Here 'Expression1' is a boolean expression, when 'Expression1' evaluates to false, then 'java.lang.AssertionError' thrown with no detail message.

2. assert Expression1 : Expression2 ;
Above form of expression is used to provide a detailed message, if Expression1 evaluates to false.
Ex:
assert((nthPrime(2) == 3)): "Wrong Prime " ;
If the 2nd prime number is not 3, then assert throws 'java.lang.AssertionError' with given message.

For Example, You written a function, which calculates nth prime number, by using assertion you can check it like below.

Example
public class NthPrime {
    public static int nthPrime(int n) {
        int candidate, count;
        for(candidate = 2, count = 0; count < n; ++candidate) {
            if (isPrime(candidate)) {
                ++count;
            }
        }
        return candidate;
    }
    
    private static boolean isPrime(int n) {
        for(int i = 2; i < n; ++i) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String args[]){
        assert((nthPrime(2) == 3)): "Wrong Prime " + nthPrime(2) ;
        
    }
}


To run the above example
Compile the example with: javac NthPrime.java
Run the example with: java -ea NthPrime

To enable assertions at runtime, -ea command line option is used, Since assertions are disabled by default.

When you tries to run the above program, you will get ' AssertionError', since ' nthPrime' method won't give correct result.

Exception in thread "main" java.lang.AssertionError: Wrong Prime4
        at NthPrime.main(NthPrime.java:23)


To make the program run, without any assertion error update the return statement as 'return candidate-1;' in nthPrime method.





                                                             Home

No comments:

Post a Comment