Java assert keyword is used to define assertion in a program. An assertion is a statement that 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 that an application primarily is for testing purposes. Assertion statements are used along with boolean expressions.
Use of assert KeywordThere are two ways in which an assert statement can be used.
First Wayassert expression;Second Way
assert expression1 : expression2Enable Assertion
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.
Example of assert KeywordLet us see an example for generation of an assertion error by the JVM −
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 above example will produce the following result −
The voter's age is 14
We can disable java assertion as well using following commands
java -da Example (or) java -disableassertions Example
where Example is the name of the Java file.
java_basic_syntax.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4