Purpose of assert keyword in Java

In Java programs assert keyword evaluates an expression, and if expression gets evaluated to false, AssertionError is thrown by JVM.

Also note that AssertionError is UnChecked Exception. So, it is not compulsory to handle AssertionError with try catch or throws.

Below is an example of using assert keyword. In this example AssertionError gets thrown is val1+val2 is >= 50.

public class AssertDemo{
public static void main(String[] a){
int val1, val2;
val1 = 34;
val2 = 30;
assert (val1+val2)<50 : "Error: Value is greater than 50"; System.out.println("Everything looks OK"); } } Output: Exception in thread "main" java.lang.AssertionError: Error: Value is greater than 50 at AssertDemo.main(AssertDemo.java:6) Also note that, by default Assertions are disabled. Please follow below steps to enable Assertions on Eclipse IDE Windows -> Preferences -> highlight the default JRE -> click Edit-> In the Default VM arguments input box, enter -ea -> click the finish button.

If you are running from command line, you can use java -ea AssertDemo