Languages
[Edit]
EN

Java - how to enable assertions?

14 points
Created by:
Root-ssh
177980

In this article we whould like to show how to enable assertions in Java.

The article describle 2 ways how to do it:

  • with command line (terminal),
  • with IntelliJ IDE.

Read below sections to see details. 

1. Java with command line example

Running program from console it is necessary to add -ea or -enableassertions paramter for java virtual machine to use assertions.

Program.java file:

public class Program {

    public static void main(String[] args) {
        String a = "text"; // or = null by default

        // some code...

        a = null; // for example: some operation caused null value

        // some code...

        assert a != null : "Variable can not be null";

        System.out.println(a.length());
    }
}

1.1. Compilation form console:

$ javac Program.java

1.2. Running from console:

$ java -ea Program

or

$ java -enableassertions Program

Output:

Exception in thread "main" java.lang.AssertionError: Variable can not be null
        at Program.main(Program.java:12)

2. IntelliJ IDEA compilation example

IntelliJ requires to add in Run/Debug Configurations window, -ea or -enableassertions paramter VM Options field.

2.1. Step 1 - create Java project

Java project with IntelliJ IDEA
Java project with IntelliJ IDEA

2.2. Step 2 - open Run / Debug configurations

Opening Run / Debug configurations with IntelliJ IDEA
Opening Run / Debug configurations with IntelliJ IDEA

2.3. Step 3 - add -ea parameter for VM options

Enable assertions parameter for IntelliJ IDEA (-ea or -enableassertions paramter)
Enable assertions parameter for IntelliJ IDEA (-ea or -enableassertions paramter)

2.4. Step 4 - running program

Running program with enabled assertions with IntelliJ IDEA
Running program with enabled assertions with IntelliJ IDEA

Alternative titles

  1. Java - how to enable assert keyword in IntelliJ IDEA
  2. Java - how to enable assert keyword with command line
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join