Why assertion is not enabled by default in java? [closed]

北战南征 提交于 2021-01-27 20:52:00

问题


By default assertion is not enabled so we have to enable it by passing -ea as jvm argumentso,

  1. Why it is not enabled by default?
  2. What is the exact use of it?
  3. If we enable does it cause performance or any other issue?

回答1:


For 1,2)Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

For 3) As you tell to compiler that the asserted code returns some thing that you expected already the outcome.If the code doesn't return the same output as you expected then there is chance of having fatal errors or unexpected memory leaks other than Assertion errors.

Hope this helps!

Documentation http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html




回答2:


Assertions can be used to verify (and document) program invariant.

It is not designed to handle exceptional conditions so you don't expect it to make a difference in production environment anyway.

It is debatable whether to enable assertions in production environment, so Java may decide arbitrarily that it will not do so by default, or may do so to not confuse those unaware.

I don't expect assertions to harm performance at all in production environment (provided you don't enable them), they can be easily optimized away (or totally ignored) by the JIT compiler.



来源:https://stackoverflow.com/questions/30324537/why-assertion-is-not-enabled-by-default-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!