assertion fails Check a field is greater than

Im trying to use a assert stmt to check if a value is greater than 1 but its not working as expected.

public class asserttest {
    static void methoda(int i){
        assert (i > 1);
        System.out.println("This is methoda");
    }
    public static void main(String[] args){
        methoda(-1);
    }
}

Output: This is methoda

Expected output:- assertionerror

I was able to fix it by enabling the assertions.

Jon Skeet
people
quotationmark

My guess is that you're getting confused by assertions not being enabled by default. Use the -enableassertions command line option:

java -enableassertions asserttest

You can also limit assertions to specific packages, and specify packages to disable using -disableassertions too.

Personally I prefer to unconditionally validate parameter values, precisely because of this - I don't like the idea of running the code in a "safe" mode in test, but then letting it loose in production with the safety off. It's like learning to drive with a seatbelt on, but then entering an F1 race without any protection...

people

See more on this question at Stackoverflow