This question already has an answer here:
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);
}
This question already has an answer here:
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);
}
JavaDoc
If the condition isn't satisfied, an
AssertionError
will be thrown.Assertions have to be enabled, though; otherwise the
assert
expression does nothing. See:http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable
Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.
In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.
It ensures that the expression returns true. Otherwise, it throws a
java.lang.AssertionError
.http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10
Although I have read a lot documentation about this one, I'm still confusing on how, when, and where to use it.
Make it very simple to understand:
When you have a similar situation like this:
You might receive warning (displaying yellow line on strB = strA.toLowerCase(); ) that strA might produce a NULL value to strB. Although you know that strB is absolutely won't be null in the end, just in case, you use assert to
1. Disable the warning.
2. Throw Exception error IF worst thing happens (when you run your application).
Sometime, when you compile your code, you don't get your result and it's a bug. But the application won't crash, and you spend a very hard time to find where is causing this bug.
So, if you put assert, like this:
you tell the compiler that strA is absolutely not a null value, it can 'peacefully' turn off the warning. IF it is NULL (worst case happens), it will stop the application and throw a bug to you to locate it.
assert
is a debugging tool that will cause the program to throw anAssertionFailed
exception if the condition is not true. In this case, the program will throw an exception if either of the two conditions following it evaluate to false.Generally speaking,assert
should not be used in production code