Question:

With reference to Java programming language, define assertion. State any one way to write an assertion.

Show Hint

Use assertions for testing internal assumptions; enable them during development for debugging.
Updated On: Jul 14, 2025
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

In Java, an assertion is a statement used to test assumptions in the program logic during development.
If the assumption is false, the program throws an AssertionError, helping detect bugs early.
Assertions are usually disabled by default and can be enabled during runtime with the -ea flag.
Syntax to write an assertion:
assert expression;
or
assert expression : errorMessage;
Example:
int age = 20;
assert age>18 : "Age must be above 18";
If the condition is false, it throws an error with the message.
Assertions are useful for debugging and testing internal logic but should not replace exception handling.
Was this answer helpful?
0
0