Java have an “assert” keyword since java 1.4


There are two kinds of syntax:

  1. assert expression1

  2. assert expression1 : expression2

expression1 must be evaluated as boolean ( true or false) while expression2 can be primitive, object, or array.

expression2 is passed into the constructor of AssertionError as an argument.


So if expression2 is evaluated as void, it’s not allowed.

void foo() {}

assert true : foo(); // cannot be compiled

How to enable or disable assertion

Assert statements will be evaluated only if assertion is enabled.

  1. through command options (aka. VM options)

ClassLoader class has some methods related to assertion setting: f918c7a0

Some restrictions and pitfalls

  1. assertion and inheritance

The following is an example:

class Derived extends Base {
    public void derivedMethod() {
        assert false : "Assertion failed:This is derive";//assertion always fails
        System.out.println("Derived Method");

    public static void main(String[] args) {
        try {
            Derived derived = new Derived();
        } catch (AssertionError ae) {

Now we use all kinds of command options and see the output results:

Best/bad usage scenarios

  1. it’s preferable to assert the arguments of private method.

You should not use assertions to check arguments in public methods because it would otherwise throw runtime exceptions: IllegalArgumentException, NullPointerException, and so forth.

  1. it’s BAD flavour that assertion has some side effects
private int a = 1;

private String foo() {
    a = 4;
    return "sss";

private void assertSomething() {
    assert false : a++; // This has a side effect
    assert false: foo(); // This also has a side effect

As assertion can be disabled, so there will be something strange to happen if you do something depending on assertion fails.

In the above example, if assertion is disabled, then the variable will be unchanged.

  1. in if-then-else and swith-case flow-control statements, you can add “assert false;” in unexpected branch of control.
switch(x) {
    case 1: ;
    case 2: ;
    case 3: 
    default: assert false : "x value is invalid: " + x;

if(a==1) {
    // some codes here
} else if {
    // some codes here
} else {
    assert false : "Normally, it cannot be here";

This is a defensive technology when you do some test. We can generalize this good style into other similar cases, for example, when you think some place in your code will never be reached. In these cases, the assertion is very useful, because once the assertion fails, there will be something critical logic errors or some programming faults.

4) You should not use assertions to validate your business logic and avoid using assertions to check or validate method arguments.