Skip to content

Assert example

Assertions are a debated topic in Java. They were implemented in such a way that they throw JVM Errors rather than Exceptions. This means they halt your program at the point of the assertion failure. Here is an example:

package com.freyer.test;

public class AssertionTest {

    /**
     * @param args
     * No args for this example
     */
    public static void main(String[] args) {
        String s = null;

        // test the proper behavior of the method
        say("hello");

        // test the improper behavior of the method
        say(s);
    }

    private static void say(String s) {
        assert s != null : "string is null";
        System.out.println(s);
    }

}

In this code, the line containing say("hello"); will cause the assertion in the say method to be true and allow the program to function normally. But the line containing say(s); will cause the assertion to fail because variable s is null.

So how can you use assertions in a production application without possibly halting it when something goes wrong? With a JVM flag. The JVM provides a means to enable and disable assertions, as follows:

java -disableassertions com.freyer.test.AssertionTest         -->  disable all assertions
java -da com.freyer.test.AssertionTest                        -->  short-hand
java -da:com.freyer.test... com.freyer.test.AssertionTest     -->  disable assertions by package name
java -da:AssertionTest com.freyer.test.AssertionTest          -->  disable assertions by class name

or

java -enableassertions com.freyer.test.AssertionTest          -->  enable all assertions
java -ea com.freyer.test.AssertionTest                        -->  short-hand
java -ea:com.freyer.test... com.freyer.test.AssertionTest     -->  enable assertions by package name
java -ea:AssertionTest com.freyer.test.AssertionTest          -->  enable assertions by class name

This syntax allows you to active and deactivate assertions globally, by package, or by classname. For greater details, see the JVM docs.