- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assertions in Java
An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program. When an assertion is executed, it is assumed to be true. If the assertion is false, the JVM will throw an Assertion error. It finds it application primarily in the testing purposes. Assertion statements are used along with boolean expressions.
Assertions in Java can be done with the help of the assert keyword. There are two ways in which an assert statement can be used.
First Way −
assert expression;
Second Way −
assert expression1 : expression2
By default, assertions are disabled in Java. In order to enable them we use the following command −
java -ea Example (or) java -enableassertions Example
where Example is the name of the Java file.
Let us see an example for generation of an assertion error by the JVM −
Example
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); } }
Output
The voter's age is 14
- Related Articles
- Enable Assertions from the command line in Java
- Assertions in Python
- Assertions in C#
- Assertions in C/C++
- Understanding Assertions Cypress
- What are assertions in Selenium with python?
- Assertions in Postman with Chai Assertion Library
- Lookbehind Assertions JavaScript Regular Expressions
- How to write Assertions in Postman with Chai Assertion Library?
- How to incorporate TestNG assertions in validating Response in Rest Assured?
- What are assertions in Python and how are they carried out?
- What are assertions available to test relational comparisons in Selenium with python?
- How to verify a JSON response body using Assertions in Rest Assured?
- Java Stream Collectors toCollection() in Java
- Java program to calculate mode in Java

Advertisements