Week 147 — What is the assert keywords and how can one use it?

Question of the Week #147
What is the assert keywords and how can one use it?
5 Replies
MrMisha | Coder
MrMisha | Coder2mo ago
The assert statement is a language feature that allows writing assumptions that should always be true. It is then possible to run the program with or without these assertions being enabled and the checks will be executed only if assertions are enabled. It can be used by writing assert followed by the condition and ending the statement with a ;:
assert 1+1 == 2;
assert "Hello World".length() == 11
assert 1+1 == 2;
assert "Hello World".length() == 11
If a program containing assert statements is executed, these statements will be ignored by default. To change this behavior, one can add -ea ("assertions enabled") to the JVM arguments. If assertions are enabled and an assertion evaluates to false, it will throw an AssertionError. For example, running the following program with java MyProgram.java (assuming it is located in MyProgram.java) prints Hello World while running it with java -ea MyProgram.java fails with an AssertionError:
void main() {
assert false;//This will fail with an AssertionError if assertions are enabled
System.out.println("Hello World");
}
void main() {
assert false;//This will fail with an AssertionError if assertions are enabled
System.out.println("Hello World");
}
In addition to enabling assertions for the entire applications, it is possible to configure this for packages or classes. To enable assertions for a package, append : followed by the the class or package name after -ea (e.g. -ea:com.example.mypackage or-ea:com.example.mypackage.MyClass) enables assertions for that package or class only. Other than enabling assertions, it is also possible to disable assertions using -da which also allows disabling assertions for a specific package or class (e.g. -da:com.example.mypackage.MyClass)
📖 Sample answer from dan1st
MrMisha | Coder
MrMisha | Coder2mo ago
In Java, the assert keyword is used to test assumptions made by the program. It provides a way for developers to catch bugs during development by verifying that a certain condition is true at runtime. If the condition evaluates to false and assertions are enabled, the JVM throws an AssertionError.
Submission from odetolaazeezatoluwatomilola
MrMisha | Coder
MrMisha | Coder2mo ago
The assert keyword in java used for assertion which are assume the code in program.
Submission from zahoobaloch
MrMisha | Coder
MrMisha | Coder2mo ago
The assert keyword allows developers to build prerequisites and invariants into their code. It evaluates a simple boolean expression, and throws a java.lang.AssertionError if it is false. Sometimes errors occur "downstream" from the root cause, because bad state or data snuck its way into the program. By checking conditions within running code, bugs can identified more easily, and unexpected errors can be avoided. For instance, take the following contrived example:
public class Factory {
private final String name;
private int counter = 0;
private final Random random = new Random();

public Factory(String name) {
this.name = name;
}

public String makeProduct() {
return "Product " + ++counter + " from " + (counter == random.nextInt() ? name.toUpperCase() : name);
}
}
public class Factory {
private final String name;
private int counter = 0;
private final Random random = new Random();

public Factory(String name) {
this.name = name;
}

public String makeProduct() {
return "Product " + ++counter + " from " + (counter == random.nextInt() ? name.toUpperCase() : name);
}
}
The makeProduct method will throw a NullPointerException every so often if the name was null. But finding the cause might be difficult to track down, because the name is not expected to be null, and the exception only happens at random times. If multiple components create Factory instances, it might not be clear which one was passing the invalid value. Adding assertions to the code can help detect when the invalid state enters the program, aborting it with a clear stack trace:
public Factory(String name) {
assert name != null : "name cannot be null";
this.name = name;
}
public Factory(String name) {
assert name != null : "name cannot be null";
this.name = name;
}
To find the source of the error, the program can be run with the -ea (or -enableassertions) flag. This will cause the assertion to fail at the point that a client creates the Factory instance with the null value, and the AssertionError will be thrown. Since this is an error (instead of an exception), the program is likely to abort, or at least print a stack trace high in the controlling code. The stack trace can then reveal the calling information, helping the developer to track down the source of the invalid data. The advantage of assertions over other checks (such as java.lang.Objects.requireNonNull) is that assertions are disabled by default. Therefore, there is no runtime penalty for performing the checks in a production environment. The assertions can be enabled during development and testing, to help shake out subtle bugs, but then disabled for production, in order to improve performance. That said, this behavior could be a disadvantage, depending on the context. The developer needs to make a choice about which "defensive" technique, if any, is appropriate for each situation.
MrMisha | Coder
MrMisha | Coder2mo ago
Also note that assertions can be selectively enabled or disabled:
java -ea:com.example.factory -ea:com.example.utils -da:com.example.utils.ReallyCommonUtils ...
java -ea:com.example.factory -ea:com.example.utils -da:com.example.utils.ReallyCommonUtils ...
This command will enable assertions for all classes in the com.example.factory and com.example.utils packages except com.example.utils.ReallyCommonUtils.
⭐ Submission from dangerously_casual

Did you find this page helpful?