In Java, assertions are used to test the correctness of assumptions made in a program. Assertions help detect logical errors during development by allowing developers to verify conditions that should always be true. If an assertion fails, the Java Virtual Machine (JVM) throws an AssertionError. Assertions are mainly used for testing purposes and debugging during development.
Assertions in JavaSyntax of Assertions
Assertions are written using the assert keyword and can be used in two ways:
1. Simple Assertion
assert expression;
2. Assertion with a Detail Message
assert expression1 : expression2;
Example: Java program to demonstrate the syntax of assertion
Java
import java.util.Scanner;
class Test {
public static void main(String args[])
{
int value = 15;
assert value >= 20 : " Underweight";
System.out.println("value is " + value);
}
}
After enabling assertions
Output:
Exception in thread "main" java.lang.AssertionError: Underweight
Enabling and Disabling Assertions
By default, assertions are disabled. We need to run the code as given. The syntax for enabling assertion statement in Java source code is:
Enable Assertions:
java -ea Test
Or
java –enableassertions Test
Here, Test is the file name.
Disabling Assertions:
The syntax for disabling assertions in java is:
java –da Test
Or
java –disableassertions Test
Here, Test is the file name.
Why use Assertions
Wherever a programmer wants to see if his/her assumptions are wrong or not.
- To make sure that an unreachable-looking code is actually unreachable.
- To make sure that assumptions written in comments are right.
if ((x & 1) == 1) {
// odd
} else {
assert (x % 2 == 0); // x must be even
}
- To make sure the default switch case is not reached.
- To check the object’s state.
- At the beginning of the method
- After method invocation.
Where not to use Assertions
- Assertions should not be used to replace error messages
- Assertions should not be used to check arguments in the public methods as they may be provided by the user. Error handling should be used to handle errors provided by users.
- Assertions should not be used on command line arguments.
Example: Java program to demonstrate assertion in Java
Java
public class Example {
public static void main(String[] args)
{
int age = 14;
assert age <= 18 : "Cannot Vote";
System.out.println("The voter's age is " + age);
}
}
OutputThe voter's age is 14
Assertion vs Normal Exception Handling
| Aspect | Assertion | Exception Handling |
|---|
| Purpose | Check logically impossible states | Handle runtime errors |
| Runtime Behavior | Can be disabled | Always executed |
| Typical Use | Development/testing | Production |
| Example | Precondition/Postcondition checks | User input validation, IO errors |
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java