What does assert do?
For example in the function:
private static int charAt(String s, int d) {
assert d >= 0 && d <= s.length();
if (d == s.length()) return -1;
return s.charAt(d);
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you launch your program with
-enableassertions(or-eafor short) then this statementis equivalent to
If you launch your program without this option, the assert statement will have no effect.
For example,
assert d >= 0 && d <= s.length();, as posted in your question, is equivalent to(If you launched with
-enableassertionsthat is.)Formally, the Java Language Specification: 14.10. The
assertStatement says the following:Where “enabled or disabled” is controlled with the
-easwitch and “An error is reported” means that anAssertionErroris thrown.And finally, a lesser known feature of
assert:You can append
: "Error message"like this:to specify what the error message of the thrown AssertionError should be.
This post has been rewritten as an article here.