Enable Assertions from the command line in Java

Java 8Object Oriented ProgrammingProgramming

By default, assertions are disabled in Java. In order to enable them we use the following command −

java -ea Example
java -enableassertions Example

Here, Example is the name of the Java file.

Let us see an example for generation of an assertion error by the JVM −


 Live Demo

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);


The voter's age is 14
Published on 08-Jan-2019 10:37:52