Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java - how to enable assertions?

0 contributions
14 points

Using Java it is possible to use assertions in few ways.

1. Java with command line example

To enable assertions is necessary to add -ea or -enableassertions paramter for java program.

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

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
Enable assertions parameter for IntelliJ IDEA

2.4. Step 4 - running program

Running program with enabled assertions with IntelliJ IDEA
Running program with enabled assertions with IntelliJ IDEA
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more