Reputation:
what should the following java code do?
public class foo{
public static void main(String[] args){
boolean mybool=false;
assert (mybool==true);
}
}
Should this throw an assertion error? and if not why not? (I'm not getting any errors!)
Upvotes: 3
Views: 845
Reputation: 81907
This makes the information if Assertions are enabled accessible in the program.
If assertions are disabled (this is the default) the assertion statement will not be executet, and mybool will have the value false.
if assertions are enabled (jvm argument -ea) the assertion will get executed, and by a side effect mybool will be set to true.
You can use that to enforce enabling or disabling of assertions. For example I have a Test in my TestSuites that failes if assertions are not enabled, in order to enforce that the assertions are always on when running the tests.
Upvotes: 0
Reputation: 403481
Java-language assertions are weird. You have to enable them when you launch the command line, and I don't like that.
For this reason, I tend to use 3rd-party libraries to do my assertions. Apache Commons Lang (via the Validator class), Spring (Via the Assert class) or even JUnit4 (via the Assert class) all provide this functionality, and it'll work regardless of VM settings. When you use Java5 static imports, they're just as easy to use as java assert, plus they're more flexible, plus they allow you to specify the error message in the exception.
Upvotes: 1
Reputation: 11876
When running the program, you have to enable assertions in the Java VM by adding '-ea' to the command line:
java -ea -jar myprogram.jar
Upvotes: 4
Reputation: 138874
This should be throwing AssertionErors
.
You need to turn on assertions if you are using Eclipse. It has them disabled by default.
To do this, add -ea to the JVM arguments.
Upvotes: 0