Sunday 17 August 2014

AssertionError

'java.lang.AssertionError' thrown to indicate that an assertion has failed.

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 ' return candidate-1;' in nthPrime method.

Related Links






                                                             Home

No comments:

Post a Comment