This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
* What does the Java Assert keyword do, and when should it be used?
What are some real-world examples to understand the key role of assertions?
Answer:
Assertions (via the Assert keyword) were added in Java 1.4. They are used to verify the correctness of invariants in code. Do not trigger them in production code and indicate errors or misuse of code paths. It can be activated at run time with options on the command -EA, but it is not turned on by default.
An example:
public Foo acquireFoo(int id) { Foo result = null; if (id > 50) { result = fooService.read(id); } else { result = new Foo(id); } assert result ! = null; return result; }Copy the code
Answer:
Suppose you write a program to control a nuclear power plant. Obviously, even the slightest error can lead to catastrophic results, so your code must be error-free (assuming that the JVM is error-free for parametric reasons).
Java is not a verifiable language, which means: you can’t calculate that the result of your operation will be perfect. The main reason for this is Pointers: they can point anywhere or anywhere, so you can’t compute a pointer with an exact value, at least not within reasonable code. Given this problem, there is no way to prove that your code as a whole is correct. What you can do, however, is prove that you at least find every error when you find it.
The idea is based on the design-by-contract (DbC) paradigm: You first define (with mathematical precision) what the method should do, and then verify it by testing it as it is actually executed
The article translated from kgs4h5t57thfb6iyuz6dqtun5y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 2…
The authors suggest that assertions are used a lot in production, especially when unit testing.
Thank you for reading this, if this article is well written and if you feel there is something to it
Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!
If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️