St.Antario
St.Antario

Reputation: 27375

How to enable assert statement to execute?

I've written the following code:

class Cl
{
    public static void main (String[] args) throws java.lang.Exception
    {
        assert true; //1
        Bar.foo();
    }

    static class Bar{
        public static void foo(){
            boolean enabled = false;
            assert enabled = true;
            System.out.println("Asserts " + 
               (enabled ? "enabled" : "disabled"));
        }
    }
}

DEMO

JLS 14.10 says:

An assert statement that is executed after its class has completed initialization is enabled if and only if the host system has determined that the top level class that lexically contains the assert statement enables assertions.

I thought I enabled assertion by assert true in Cl class, but it's still not working. How can I enable an assertion regarding to what JLS said?

Upvotes: 2

Views: 1746

Answers (3)

Stephen C
Stephen C

Reputation: 718758

The other answers explain how to enable assertions. (Note that you can enable or disable them for all classes, for the classes in a given package, or for individual classes.)

I just want to explain what assert true; actually does.

It doesn't enable or disable assertions. That's not what an assert statement "means". Indeed, by the time you execute that statement, it would be too late to enable or disable assertions for either C1, and probably for Bar as well. Assertions can only be enabled or disabled for a class before the class has be initialized. That happens (at most) once for any given class.

What it actually does (if assertions are enabled ...) is to evaluate the expression true and test whether it is true. Which it always will be. In short, it is a no-op.

Upvotes: 2

Akash Thakare
Akash Thakare

Reputation: 22972

Run Your program like this,

java -ea YourClass

-ea means enable assertion and after running like this your assertions will be executed during runtime otherwise it just jump the assert statements.

If you are using eclipse go to Run Configuration and write -ea in VM Arguments and Run.

If you are trying to enable assertion programmatically you can try this,

     boolean enabled = false;
     ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
     assert enabled = true;
     System.out.println("Asserts " + 
        (enabled ? "enabled" : "disabled"));

Upvotes: 3

mikea
mikea

Reputation: 6667

Add the -ea option to your java command line when you run your program

Upvotes: 6

Related Questions