Assert in Java
By Sonal Dwivedi, Community Contributor - December 5, 2024
An assertion is a statement in Java that tests assumptions about the program. The assert keyword is used to achieve assertions in Java.
Before the release of JDK 1.4, developers used custom assertion methods, logs, and comments to document their assumptions about program accuracy. Assert was introduced in JDK 1.4, which provided a more structured and integrated way to handle assertions in Java.
- What is Assert in Java?
- Why are Java asserts disabled by default?
- Syntax of Assert in Java
- When to use assertions in Java code
- How to Use Assertions in Java with Examples
- When not to use Assertions in Java
- Assertions vs. Exceptions in Java
- Common Challenges with Assertions in Java
- Best Practices of Using Assertions in Java
What is Assert in Java?
Java assert evaluates a boolean expression and throws an AssertionError exception if the expression returns false after evaluation. This helps surface bugs during the development by verifying that certain conditions hold.
Assert plays a vital role in enhancing the robustness and maintainability of Java code. It reduces the need for extensive error-checking code, making the program logic more concise and clearer.
Why are Java asserts disabled by default?
If assertions were enabled by default, developers might wrongly depend on them for important program logic or input validation. In such a scenario, the absence of an assertion check would result in unexpected behavior in production.
Java encourages explicit error handling by keeping asserts disabled by default.
If assertions were enabled by default, they would add an overhead to program execution. Assertions are primarily used for debugging, and by keeping them disabled by default, Java encourages developers to write robust and clear production code without depending on assertions for critical logic.
Syntax of Assert in Java
The assert statement can be written in 2 ways:
Basic assertion: It checks a condition and throws an Assertion error if the condition is false.
Syntax:
assert expression;
Example:
int num=9; assert num>0;
An example would help here
assert number > 0;
Assertion with error message: It allows you to provide a custom message that will be included in the assertion error
Syntax:
assert expression1 : “Error message”;
Example:
int age =20; assert age >0 : “Age cannot be negative.Given age is ” +age;
An example would help here
assert age > 0 : "Error: Age cannot be negative. Given age is " + age;
When to use assertions in Java code
1. Unreachable codes: The code which is not executed when we run the program is unreachable. You should use assertions to ensure that the unreachable codes are unreachable.
switch (vowel) { case "a": System.out.println("a is vowel"); break; case "e": System.out.println("e is vowel"); break; case "i": System.out.println("i is vowel"); break; case "o": System.out.println("o is vowel"); break; case "u": System.out.println("u is vowel"); }
For example:
If there is a switch case with no default case, then you must use assertions. If there is no default case, the programmer believes that one of the cases will always be executed.
However, there might be some cases in which the assumption is false. Assumptions like these should always be checked using an assertion to ensure the default switch case is not reached.
default: assert false: vowel + “is not a vowel”;
2. Documenting assumptions: Many programmers use comments to document the underlying assumptions. For example:
int num=-5; if(num>0){ System.out.println(“Number is positive”); }else{ // It is known that number is negative }
Note: Comments can become old-dated, out of sync, or interpreted differently by different programmers. Therefore, always use assertions in such scenarios.
int num=-5; assert number >0 : “Number is negative”;
3. Development and testing: Assertions are mainly used during the development and testing. With the help of assertions, bugs can be caught up early in the STLC cycle, which will help expedite the completion of development and testing cycles.
Also Read: Difference between SDLC and STLC
How to Use Assertions in Java with Examples
Below is an explanation of using assertions in Java with examples:
Basic assertion example:
class Assertions { public static void main(String args[]) { int age = 15; assert age >= 20; System.out.println("value is " + age); } } Open command prompt and run this program using below command: java Assertions.java
It will run without throwing any assertion, andthe value will be printed.
This is because assertions are, by default, disabled at runtime. You can enable them by using the -ea or -enableassertions flag while running.
After using -ea flag, the test failed, andan assertion error got displayed.
Assertion with error message example:
class Assertions { public static void main(String args[]) { int age = 15; assert age >= 20: "Less than 20"; System.out.println("value is " + age); } }
In this example, the code checks that the age is greater than 20, and a custom message is provided if the assertion fails.
Use -da or -disableassertions option to disable assertions.
Read More: Junit Assert
When not to use Assertions in Java
Assertions help to test for scenarios, conditions, and application flow results. They are helpful in catching programming errors and validating assumptions.
Any scenario other than these should be handled using error or exception handling.
- User input validation: If a user passes invalid input, assertion is not the right way to handle it. Instead, it should be validated using proper error-handling mechanisms such as throwing exceptions.
- Argument checks in public methods: Assertion should not be used to check arguments in public methods as the user may provide them. If an assertion is used to check these arguments, the condition may fail, resulting in AssertionError.
- Error handling: Assertions should not be used for regular error handling. In environmental issues such as database running status or if a website URL exists, assert should be avoided.
Also Read: Understanding Playwright Assertions
Assertions vs. Exceptions in Java
Assertion is used for debugging the required assumptions to be checked at runtime, whereas an exception is an abnormal event that arises during program execution and disrupts the program’s normal flow.
Below are some differences between both:
Parameter | Assertions | Exceptions |
---|---|---|
Default State | Disabled by default | Always enabled |
Primary Purpose | Debugging and verifying assumptions during development | Handling errors and exceptional conditions that occur during program execution |
Nature | Catch programming errors by checking conditions that should always be true | Represent conditions the program might want to catch and handle gracefully |
Production Impact | No overhead on production code as they can be turned off when required | May cause performance overhead when thrown |
Common Challenges with Assertions in Java
Below are some common challenges and limitations with assertions in Java:
- Inappropriate usage: Instead of handling exceptions, developers may sometimes overuse or misuse assertions by applying them at multiple places in code. Assertions should only be used at appropriate scenarios and should be avoided for internal logic and invariants.
- Complex conditions: Creating complex assertions may be difficult to understand and analyse, which makes debugging harder when they fail. Always break down complex assertions into smaller ones, which makes them simple and easy to understand.
- Unclear messages: Limited or confusing context in assertion makes it hard to understand and diagnose failures. Assertion messages should always be concise and clear.
- Performance overhead: Assertions are disabled by nature, and even if assertion is enabled, it can be disabled anytime as per needed. However, implementing many assertions can still introduce overhead in performance during development.
- Incompatible for all conditions: In a program, certain conditions throw exceptions, and some should be checked with assertions. Conditions such as user input errors are better handled with exceptions rather than assertions. In a scenario with multiple conditions to be tested, differentiate the conditions that throw exceptions and which can be handled by assertions.
Best Practices of Using Assertions in Java
Here are some best practices of using Assertions in Java:
- Use for internal invariants: Assertions should be used to check the program’s internal invariants and assumptions and for user input validation or external checks.
- Not to be used in public methods: Assertions should be avoided in public methods for checking arguments. Exceptions should be used instead, such as NullPointerException or IllegalArgumentException.
- Give meaningful messages: Always provide meaningful and descriptive messages in asserts to make the debugging easier.
- Use assertions wisely: Remember that using asserts would create an overhead during development, so use them only when required.
- Review the asserts periodically: Constantly review them to ensure they are still adding value to the code. Unnecessary and redundant assertions should be removed if not used.
Conclusion
Assertions in Java are very powerful for enhancing code correctness and helping in debugging.
By using assertions effectively, developers can develop more robust applications and reduce the chances of encountering unexpected behavior in production. Also, assertions should be used wisely and only when needed to reduce production overhead.