Languages
[Edit]
EN

Java - how to enable assertions?

14 points
Created by:
Root-ssh
6663

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
Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.